If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?
For example:
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
The output is "Bar" which means that the object was passed as a reference.
Best Answer
Pass a
ref
if you want to change what the object is:After calling DoSomething,
t
does not refer to the originalnew TestRef
, but refers to a completely different object.This may be useful too if you want to change the value of an immutable object, e.g. a
string
. You cannot change the value of astring
once it has been created. But by using aref
, you could create a function that changes the string for another one that has a different value.It is not a good idea to use
ref
unless it is needed. Usingref
gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the
ref
keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g.int
), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns: