0

The TestMethod of this sample code

public class Test<T> where T : class
{
    public void TestMethod(T param)
    {
        PrivateMethod(param);
    }

    private void PrivateMethod(object obj)
    {

    }
}

compiles into this IL code:

IL_0000:  ldarg.0
IL_0001:  ldarg.1
IL_0002:  box        !T
IL_0007:  call       instance void class SensorPositioner2.Test`1<!T>::PrivateMethod(object)
IL_000c:  ret

As I see the box instruction, would a new object be created during the TestMethod call?

If so, how can I avoid this? If not, why box is needed here?

lilo0
  • 895
  • 9
  • 12
  • 1
    A new object would not be created for a reference type, because it will be optimised away by the Jitter (see the dupe for details). – Matthew Watson Oct 07 '20 at 07:53
  • @MatthewWatson, sorry, I can't understand where to get the details. May you clarify this, probably as an answer. – lilo0 Oct 07 '20 at 08:47
  • 1
    Click the link at the top of your question underneath where it says "This question already has answers here". – Matthew Watson Oct 07 '20 at 09:23

1 Answers1

2

The boxing is required because of the object parameter in the PrivateMethod(). You could change the signature of PrivateMethod to use Generic Type instead of object to avoid boxing.

private void PrivateMethod(T obj)
{

}

This would translate to

 
IL_0001:  ldarg.0     
IL_0002:  ldarg.1     
IL_0003:  call        UserQuery+Test<>.PrivateMethod  // Your method
IL_0008:  nop         
IL_0009:  ret 
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • No, I can't. PrivateMethod simulates an API method with an object parameter. That's the point of the question. – lilo0 Oct 07 '20 at 08:25