I was curious, so I made my own test code myself:
public interface ITest { int Value { get; set; } } public struct TestStruct : ITest { public int Value { get; set; } } private static void TestMethodGeneric<T>(T value) where T : ITest { } private static void TestMethodNonGeneric(ITest value) { }
And in my main method, I use both calls:
TestStruct ts = new TestStruct {Value = 10}; TestMethodNonGeneric(ts); TestMethodGeneric(ts);
And this is the result of the IL code:
not common:
IL_0031: ldloc.0 // ts IL_0032: box Tests.Program/TestStruct IL_0037: call void Tests.Program::TestMethodNonGeneric(class Tests.Program/ITest) IL_003c: nop
Generic:
IL_0059: ldloc.0 // ts IL_005a: call void Tests.Program::TestMethodGeneric<valuetype Tests.Program/TestStruct>(!!0) IL_005f: nop
So, you see that the general version uses a specific type, and therefore boxing does not occur.
In the non-generic version, the struct value should be dropped to ITest , and therefore it will be inserted into the box. So the generic version has a (very tiny) performance advantage.
Only my two cents, perhaps other more or less important differences in the two approaches.
RenΓ© vogt
source share