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
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.