C# Tips

C# Tip Article

Pass reference type using "ref"

When a reference type object is passed to another method, one can add "ref" keyword in front of the parameter. Since the parameter is already referencce type, any property change of the object in the callee will be passed to the caller, regardless of using "ref" keyword.

So what is the difference?

As shown in the example below, the difference is, if ref is used, the parameter object can be replaced by another object in the callee while it is not possible when "ref" is not used.

class Program
{
	static void Main(string[] args)
	{
		Person p = new Person(1, "Tom");
		
		// (1) without ref
		Change(p);
		// OUTPUT: 10, Jane
		Console.WriteLine("{0},{1}", p.Id, p.Name);

		// (2) with ref
		Change(ref p);
		// OUTPUT: 100, Jerry
		Console.WriteLine("{0},{1}", p.Id, p.Name);
	}

	static void Change(Person a)
	{
		// Updating property of the object a 
		a.Id = 10;
		a.Name = "Jane";

		// a is replaced by another object but the caller will ignore it.
		a = new Person(100, "Jerry");
	}

	static void Change(ref Person a)
	{
		a.Id = 10;
		a.Name = "Jane";

		// a is replaced by another object and the caller will have new object
		a = new Person(100, "Jerry");
	}
}

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

	public Person(int id, string name)
	{
		this.Id = id;
		this.Name = name;
	}
}