Passing a class as a ref parameter in C# does not always work as expected. Can anyone explain?

前端 未结 4 445
慢半拍i
慢半拍i 2020-12-08 14:37

I always thought that a method parameter with a class type is passed as a reference parameter by default. Apparently that is not always the case. Consider these unit tests

4条回答
  •  一个人的身影
    2020-12-08 15:18

    The AssignmentTest uses TestAssignmentMethod which only changes the object reference passed by value.

    So the object itself is passed by reference but the reference to the object is passed by value. so when you do:

    testClass = new TestRefClass() { TestInt = 1 };
    

    You are changing the local copied reference passed to the method not the reference you have in the test.

    So here:

    [TestMethod]
    public void AssignmentTest()
    {
        var testObj = new TestRefClass() { TestInt = 0 };
        TestAssignmentMethod(testObj);
        Assert.IsTrue(testObj.TestInt == 1);
    }
    

    testObj is a reference variable. When you pass it to TestAssignmentMethod(testObj);, the refernce is passed by value. so when you change it in the method, original reference still points to the same object.

提交回复
热议问题