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

前端 未结 4 430
慢半拍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:07

    The default convention for parameters in C# is pass by value. This is true whether the parameter is a class or struct. In the class case just the reference is passed by value while in the struct case a shallow copy of the entire object is passed.

    When you enter the TestAssignmentMethod there are 2 references to a single object: testObj which lives in AssignmentTest and testClass which lives in TestAssignmentMethod. If you were to mutate the actual object via testClass or testObj it would be visible to both references since they both point to the same object. In the first line though you execute

    testClass = new TestRefClass() { TestInt = 1 }
    

    This creates a new object and points testClass to it. This doesn't alter where the testObj reference points in any way because testClass is an independent copy. There are now 2 objects and 2 references which each reference pointing to a different object instance.

    If you want pass by reference semantics you need to use a ref parameter.

提交回复
热议问题