find a location for property in a new city

Wednesday 7 December 2016

Reference object with ref keyword on a method. What's the point?

I wondered the other day what the point is in making a method parameter a ref when it is already a reference type. After playing around for a bit I came up with some concise code to illustrate the difference.

The difference is that, although you can modify the reference object that was passed in with both methods. Changing the reference entirely (i.e. pointing to a different object) only has an effect outside the scope of the method if the object was passed through with the ref keyword.

This code should explain better than English:

void Main()
{
 var t1 = new Thing();
 Test(t1);
 t1.Write(); // Chair
 
 var t2 = new Thing();
 Test(ref t2);
 t2.Write(); // Table
}

void Test(Thing t)
{
 t.Name = "Chair";
 t = new Thing { Name = "Table" };
}

void Test(ref Thing t)
{
 t.Name = "Chair";
 t = new Thing { Name = "Table" };
}

class Thing
{
 public string Name { get; set; }
 public void Write() => Console.WriteLine(Name);
}

Follow britishdev on Twitter