I looked at the similar questions and read some articles. THis article has some pictures which makes it clear.
SomeObject so = new SomeObject();
somefunction(so);
Console.write(so.x); // will print 1
SomeObject so1 = new SomeObject();
somefunctionByRef(so1);
Console.write(so1.x); // will print 1
static void somefunction(SomeObject so)
{
so.x = 1;
}
public void somefunctionByRef(ref SomeObject so)
{
so.x = 1;
}
Both of the methods have the same effect on this reference type. so why choose ref keyword for reference types?
is it a bad practice (possibly false) to use somefunction(SomeObject so) and modify the object inside the method and expect the changes without using the ref keyword?
The default parameter passing in .Net is done by value. This is true for both value types and reference types. The difference is that with a reference type you are passing a reference to the instance by value vs. the actual object.
The effect is the
soreference in the original function and someFunction are independent. Changing which instance the reference refers to has no affect on the other. However because they refer to the same object they can see mutations to that object done by the other (this is why x changes in your example)The
refmodifier causes the parameter to be passed by reference instead of value. Effectively there is no copy of the reference, thesoin both the original and calling function are the same reference. So resetting one resets the other