Set the null property from outside the instance

I have identified the following behavior, which is difficult for me to understand.

I assumed that you could set the Object A property to Object B, manipulate the object B, and that the changes would be transferred to the Object A property (because it is the same object). I expected this unit test to pass, but on the last line it fails 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;
        }
    }
+4
source share
3 answers

This line

child = null;

Don't do what you think. It cancels the reference to the object Childthat your method has TestObject(), but it does not affect the reference to the same object Childthat is stored by the object Parent:

Before you assign child = null:

Before the change

child = null:

After the change

Assert.IsNull(parent.Child);

: parent.Child Child, .

, child.Name = null, parent.Child.Name null:

child.Name = null;
Assert.IsNull(parent.Child.Name);
+13

, . Child Parent, . , Child Parent.child , . Child Parent.child , , . , Child null, , (null), , Parent.child, , , , child = null, - , . ,

Child child2 = child;
child = null;

child2 null, child2 Child, , , , , .

+5

The Child property is a reference to the actual Child object in memory. Your local "child" variable is another different reference to the same object. When you set your local child to null, it does not touch your parent link to it. If you set the Name property in any link that changes the actual object, and you will see that it is reflected through both links to it.

+3
source

All Articles