How to assign a reference to a variable in C#

CsharpProgrammingServer Side Programming

To assign reference to a variable, use the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. Declare the reference parameters using the ref keyword.

Let us see an example −

Here, we are swapping two values using the ref keyword −


 Live Demo

using System;

namespace Demo {
   class Program {
      public void swap(ref int x, ref int y) {
         int temp;

         temp = x; /* save the value of x */
         x = y; /* put y into x */
         y = temp; /* put temp into y */

      static void Main(string[] args) {
         Program p = new Program();

         /* local variable definition */
         int a = 99;
         int b = 110;

         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);

         /* calling a function to swap the values */
         p.swap(ref a, ref b);

         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);



Before swap, value of a : 99
Before swap, value of b : 110
After swap, value of a : 110
After swap, value of b : 99
Updated on 20-Jun-2020 10:57:25