Call limited

For this code:

class Program { static void Main() { Console.WriteLine(new MyStruct().ToString()); } struct MyStruct { } } 

C # compiler generates constrained callvirt IL code.

This article says:

For example, if the value type V overrides the Object.ToString () method, the invocation command is called V.ToString (); if it is not, the box command and the Object.ToString () callvirt instruction are issued. A version issue may occur <...> if an override is added later.

So my question is: why would this be a problem in this case if the compiler would generate the box code rather than a limited call?

+4
source share
1 answer

The box creates a copy of the instance in question. The instance methods of value types are allowed to change the instance to which they are called, and if they do, silently invoking the method on the copy - this is not what needs to be done.

 static class Program { static void Main() { var myStruct = new MyStruct(); Console.WriteLine(myStruct.i); // prints 0 Console.WriteLine(myStruct.ToString()); // modifies myStruct, not a copy of myStruct Console.WriteLine(myStruct.i); // prints 1 } struct MyStruct { public int i; public override string ToString() { i = 1; return base.ToString(); } } } 
+7
source

All Articles