I’ve created a class that takes in an object as a parameter by ref. When it takes this object in it’s construct it is null. Why does it stay null (uninitialized)?
// example code, not real
class Test{
object parent;
public Test (ref object _parent)
{
parent = _parent;
}
}
object n = null;
Test t = new Test (ref n);
n = new Something ();
When I tried it with a different class (http://pastebin.com/PpbKEufr), it stayed null
Yes,
parentwill staynullregardless of what you eventually assign to the variablen. Therefkeyword will pass the actual reference ton(as opposed to a copy of it) into your method, and is typically used if your method was intended to assign a new object instance to the parameter.Inside your method, you are making a copy of the reference that
npoints to, in this casenull. When the method completes bothnandparentpoint tonull. When later you assign to n, you haven’t changed the object to which n and parent point, rather you have askednto point to a new location, leavingparentstill pointing tonull.If you were to create an instance of an object and assign it to
n, thenparentwould point to the same object and any changes to that object’s properties would be visible to your class. The same would be true if you did not pass the parameter asref, as the reference copy also would point to the same object instance.Hope that helps.