If you create a class in .NET it will be a reference type. In this example I’m setting the name of MyClass inside of SomeMethod. Now inside the Main method I do not really need to assign back the return value from SomeMethod because the parameter passed in is a reference type. I’m wanting the instance in the main method to have the new updated name “John” and it does.
I often assignee back the return value anyway for readability, even though this isn’t needed to get the updated properties reassigned to my origin instance in main. My assumption is that the compiler is smart enough not to recreate a new reference of MyClass inside the Main method. Is that true? Or does the compiler actually create a new reference and pointing to the updated values when assigning itself the return value?
//My class will be a reference type
public class MyClass
{
public int ID { get; set; }
public string name { get; set; }
}
public class Main
{
//Main method of application
public void Main()
{
MyClass myClass = new MyClass();
//return value back to itself
myClass = SomeMethod(myClass);
}
public MyClass SomeMethod(MyClass myClass)
{
myClass.name = "John";
return myClass;
}
}
Here is the IL
instance void Main1 () cil managed
{
// Method begins at RVA 0x207c
// Code size 15 (0xf)
.maxstack 2
.locals init (
[0] class Test.MyClass myClass
)
IL_0000: newobj instance void Test.MyClass::.ctor()
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: call instance class Test.MyClass Test.Main::SomeMethod(class Test.MyClass)
IL_000d: stloc.0
IL_000e: ret
} // end of method Main::Main1
To answer your question, yes the compiler is smart enough to not reassign the return value to the same object. If we open your code with Reflector or dotPeek, your code :
is simply transform to :
Even if we do something with the reassign variable, it is still remove by the compiler. For example, the compiler transform this :
to that :
But like Lews Therin and Robert Jeppesen said, you shouldn’t do that because it is bad practice and could lead to misunderstanding