Why does generic method with constraint of T: class result in boxing?

You don't have to worry about any performance-degradations from the box instruction because if its argument is a reference type, the box instruction does nothing. Though it's still strange that the box instruction has even been created (maybe lazyiness/easier design at code generation?).


I'm not sure why any boxing is ocurring. One possible way to avoid the boxing is to not use it. Just recompile without the boxing. Ex:

.assembly recomp_srp
{
    .ver 1:0:0:0
}

.class public auto ansi FixedPBF
{

.method public instance void .ctor() cil managed
{

}

.method hidebysig public instance void SetRefProperty<class T>(!!T& propertyBackingField, !!T newValue) cil managed
{
    .maxstack 2    
        .locals init ( bool isDifferent, bool CS$4$0000)

        ldc.i4.0
        stloc.0
        ldarg.1
        ldobj !!T
        ldarg.2
        ceq
        stloc.1
        ldloc.1
        brtrue.s L_0001
        ldc.i4.1
        stloc.0
        L_0001: ret

}

}

...if you save to a file recomp_srp.msil you can simply recompile as such:

ildasm /dll recomp_srp.msil

And it runs OK without the boxing on my end:

        FixedPBF TestFixedPBF = new FixedPBF();

        TestFixedPBF.SetRefProperty<string>(ref TestField, "test2");

...of course, I changed it from protected to public, you would need to make the change back again and provide the rest of your implementation.