Reputation: 103
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
Upvotes: 0
Views: 518
Reputation: 176259
It is not possible to change a private member of a class that way as this would break the idea of encapsulation.
In order to change (i.e. replace) an object stored in a private field you must do so explicitly via a public property or method of that class, e.g.
class Test
{
object parent;
public Test (ref object _parent)
{
parent = _parent;
}
public object Parent
{
get { return parent; }
set { parent = value; }
}
}
object n = null;
Test t = new Test (ref n);
n = new Something ();
t.Parent = n;
This way the language makes sure that data of an object cannot (accidentally) be changed from the outside, which might lead to the strangest effects.
Upvotes: 2
Reputation: 7875
Yes, parent
will stay null
regardless of what you eventually assign to the variable n
. The ref
keyword will pass the actual reference to n
(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 n
points to, in this case null
. When the method completes both n
and parent
point to null
. When later you assign to n, you haven't changed the object to which n and parent point, rather you have asked n
to point to a new location, leaving parent
still pointing to null
.
If you were to create an instance of an object and assign it to n
, then parent
would 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 as ref
, as the reference copy also would point to the same object instance.
Hope that helps.
Upvotes: 4
Reputation: 23790
The ref arguments in C# refer to the instance "pointed" by the argument.
For example, if you'd change _parent
in the constructor and store it in other instance, then n
would change too.
In the posted code you're copying the referenced instance (null
) into parent
. Meaning, it copies the referenced instance into the field and not the reference of the argument itself.
For example, method that changes the ref argument:
public void M(ref object arg)
{
arg = new object();
}
And a usage example:
[Test]
public void SetReferenceArgument()
{
var myClass = new MyClass();
object arg = null;
myClass.M(ref arg);
Assert.That(arg, Is.Not.Null);
}
ref argument lets us assign an instance into the argument which will change the reference both in the of the method and in the context of the caller.
Upvotes: 1