X

C# the use of ref keyword

dotnet C#

In C# when using the ref keyword it causes an argument to be passed by reference, not by value.
In order to use a ref as a parameter, both the method definition and the calling method must explicitly use the ref keyword, and also the variable must be initialized before passing in.

In the example below we have two methods, one using the ref keyword the other not.


void Increment(int x)
{
  x = x + 1;
}


void IncrementWithRef(ref int y)
{
  y = y + 1;
}

int x = 1;
Increment(x); 

Console.WriteLine(x);//x is still 1

Increment(ref x);
Console.WriteLine(x);//x is now 2

But what about objects that are reference types. Here is where the confusion starts that the concept of passing by reference with the concept of reference types, the concepts are not the same. A method parameter can pass in a ref type regardless of its type (value or reference).

Below is an example that shows when a Person object reference type is used.

public class Person
{
  public string Name { get; set; }
}

void NameChange(Person p)
{
   p.Name = "John";
}

void NameChangeRef(ref Person p)
{
 p = new Person{ Name = "Ref Person" };
}

Person p = new Person { Name = "Peter" };
	
Console.WriteLine(p.Name); //output is Peter
	
NameChange(p);
	
Console.WriteLine(p.Name); //output is John we have changed the reference type property but not the object
	
NameChangeRef(ref p); 
	
Console.WriteLine(p.Name); //output is Ref Person we have changed the object that p points to

Last but not least I personally do not recommend using ref keyword and also from
The Framework Design Guidelines it also recommend to avoid using ref.

Categories: .NET C#
Taswar Bhatti:
Related Post