Monday, October 26, 2009

Passing arguments as 'ref' in C#.

What confuses me about passing a variable as reference (ref) is the concept of value types and reference types in C#.
Since, reference types are always passed by reference, why would we need to pass a reference type as 'ref' argument?

The difference is that passing an argument as 'ref' allows the method to change the reference also (memory address stored in the variable), which can not be done otherwise. A reference type allows the calling method to change the state of the instance (some fields), while passing an argument as 'ref' allows the calling method to assign a new instance to the variable.

Sample Code:

public class PlayWithRef {
public class Employee {
public string Name { get; set; }
public override string ToString() {
return Name;
}
}
public static void DoIt() {
var emp=new Employee{Name="Rina"};
ModifyMe(emp);
Console.WriteLine(emp);
ModifyMeAlso(ref emp);
Console.WriteLine(emp);
}
public static void ModifyMe(Employee str) {
str=new Employee { Name="NonRef Rina" };
}
public static void ModifyMeAlso(ref Employee str) {
str=new Employee{Name="Ref Rina"};
}
}

Essentially what happens is, passing an argument sends the heap memory address and the argument can access the instance lying in that address and can modify its instance/fields but can not make the original variable point to a new memory address, which is possible when the variable is send as 'ref'.

No comments:

Post a Comment