Useless boxing with generic types

94 Views Asked by At

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?

1

There are 1 best solutions below

1
On

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