title: Boxing of user-defined value types
body: <p>According to MSDN, if a struct were defined, that struct should override all methods inherited from the object class. That is recommended to avoid the unnecessary boxing when calling any inherited method such as ToString.</p>
  
  <p>According to the MSDN, to determine if and when boxing occurs, an IL instruction "box" can be found in the MSIL code.</p>
  
  <p>I wrote the following test to see the boxing.</p>
  
  <pre><code>using System;
  
  namespace TestingBoxing
  {
      public struct StructX
      {
          public int member1;
          public int member2;
      }
  
      public class Program
      {
          public static void Main(string[] args)
          {
              StructX s1;
  
              s1.member1 = 2;
              s1.member2 = 5;
  
              string str = s1.ToString();
  
              Console.WriteLine(str);
          }
      }
  }
  </code></pre>
  
  <p>However, the boxing instruction cannot be seen in the MSIL code below although ToString is called without being overridden in the struct definition.</p>
  
  <pre><code>.method public hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       37 (0x25)
    .maxstack  2
    .locals init ([0] valuetype TestingBoxing.StructX s1,
             [1] string str)
    IL_0000:  ldloca.s   s1
    IL_0002:  ldc.i4.2
    IL_0003:  stfld      int32 TestingBoxing.StructX::member1
    IL_0008:  ldloca.s   s1
    IL_000a:  ldc.i4.5
    IL_000b:  stfld      int32 TestingBoxing.StructX::member2
    IL_0010:  ldloca.s   s1
    IL_0012:  constrained. TestingBoxing.StructX
    IL_0018:  callvirt   instance string [mscorlib]System.Object::ToString()
    IL_001d:  stloc.1
    IL_001e:  ldloc.1
    IL_001f:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_0024:  ret
  } // end of method Program::Main 
  </code></pre>
  
  <p>How that could be explained ?</p>
  
  <p>Reference article: <a href="http://msdn.microsoft.com/en-us/library/ms973858.aspx#code-snippet-6" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms973858.aspx#code-snippet-6</a></p>