What’s C# language specification for the following behavior. The values of the attributes are retained but the new instance (either null or new object) isn’t updated to the actual parameter. It’s basically functions as ref except changing the object it points to.
The object in the main function remained intact (not null) but the string attribute has been changed to “Hello World”
class Program
{
class MyClass
{
public string str;
}
static void MyMethod(MyClass obj)
{
obj.str = "Hello World";
obj = null;
}
static void Main(string[] args)
{
MyClass o = new MyClass();
o.str = "Hello";
Console.WriteLine(o.str);
MyMethod(o);
Console.WriteLine(o.str); // prints "Hello World"
}
}
In .NET languages, object references are passed by value.
So what does this mean? Conceptually your code is the same as this, with the pointers made explicit:
The parameter passed to
MyMethodis the value of the pointero, pointing to aMyClassinstance. You can dereference the pointer to set the value ofstr, but setting the actual pointer value to null doesn’t affect the variable in the calling method.You can pass the reference by reference by doing this:
What’s C# language specification for the following behavior. The values of the attributes are retained but the new instance (either null or new object) isn’t updated to the actual parameter. It’s basically functions as ref except changing the object it points to.