I have identified the following behavior which I'm having a hard time understanding.
I was assuming that you could set the property of an Object A to an Object B, manipulate the Object B and that the changes would be carried on to the property of Object A (because it is the same object). I was expecting this unit test to pass but it fails at the last line when setting B to null. Why?
[TestMethod]
public void TestObject()
{
Child child = new Child();
var parent = new Parent(child);
child.Name = "John";
Assert.AreEqual(parent.Child.Name, "John");
child = null;
Assert.IsNull(parent.Child);
}
public class Child
{
public string Name { get; set; }
}
public class Parent
{
public Child Child { get; set; }
public Parent(Child kid)
{
Child = kid;
}
}
This line
child = null;
is not doing what you think it does. It nulls out the reference to the Child
object that your TestObject()
method holds, but it has no effect on the reference to the same Child
object held by the Parent
object:
Before you assign child = null
:
After you assign child = null
:
That is why
Assert.IsNull(parent.Child);
fails: parent.Child
reference is different from child
reference that you have nulled out.
On the other hand, if you do child.Name = null
then parent.Child.Name
would become null
as well:
child.Name = null;
Assert.IsNull(parent.Child.Name);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With