Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set property to null from outside of the instance

Tags:

c#

.net

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;
        }
    }
like image 257
Keysharpener Avatar asked Nov 29 '22 10:11

Keysharpener


1 Answers

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:

Before the change

After you assign child = null:

After the change

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);
like image 109
Sergey Kalinichenko Avatar answered Dec 08 '22 14:12

Sergey Kalinichenko