2010-08-05

Using ref Keyword with Reference Types in C#

One of our developers was using the ref keyword in a method that needed to replace the value of a property of the method's parameter.

In other words...


public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}

public static class ReferenceExample
{
public static void Main()
{
var person = new Person
{
Name = "Mark",
Email = "none@none.com",
};

Save(ref person);

Console.WriteLine(person.ID);
Console.ReadLine();
}

public static void Save(ref Person person)
{
person.ID = 1; // Pretend this saves to a database or something
}
}


The thinking is correct. Person needs to be passed by reference. So why not use the ref keyword, right? Well...Person is already a reference type. So if we are just replacing properties, we don't need the ref keyword. Removing it changes nothing with our code. The program still outputs 1.

This begs the question -- Why even have the ref keyword? The reason for it is to pass the entire parameter by reference. This means that we can redefine a newly instantiated person.

In other words...



public static class ReferenceExample
{
public static void Main()
{
var person = new Person
{
Name = "Mark",
Email = "none@none.com",
};

Save(ref person);

Console.WriteLine(person.ID);
Console.WriteLine(person.Name);
Console.ReadLine();
}

public static void Save(ref Person person)
{
person = new Person
{
Name = "Bill",
Email = "adventures@phonebooth.com",
ID = 2,
};
}
}


Try running the above with and without the ref keyword. If you use it with the ref keyword, the Person will be "Bill". If you use it without, the person will be "Mark".

Seems simple enough but I'm surprised how many developers don't (or didn't!) realize this difference.

No comments: