It is important to note that pass by reference in C# has a specific meaning. In the case of a property, the property ends up pointing to the same address as that of the object it was set to. In the case of passing objects to a function, C# uses pass reference by value semantics. That means that the reference itself is copied, so a new pointer points to the same address as the object that was passed. This prevents a function from nullifying any original pointer by setting its parameters to null. To actually pass an original reference, the 'ref' keyword must be used:
class SomeClass
{
public object MyObjectProperty { get; set; }
}
var someClass = new SomeClass();
object someObject = new object();
someClass.MyObjectProperty = someObject; // Makes MyObjectProperty point to the same location as someObject
In the following case, reference by value semantics are used:
void MyMethod(object someObject)
{
someObject = null;
}
object someObject = new object();
MyMethod(someObject);
Console.WriteLine(someObject == null); // Prints false
In the following case, actual pass by reference semantics are used:
void MyMethod(ref object someObject)
{
someObject = null;
}
object someObject = new object();
MyMethod(ref someObject);
Console.WriteLine(someObject == null); // Prints true