Embedding an interface into a parameter of a generic method VS Embedding an interface into a method argument

Im pretty confused by what I found in a programming course.

In short - I found a method that has this construction:

public void MethodA<T>(T a) where T : IComparable { //... } 

And as far as I know - the same exact effect that we can achieve using only this:

  public void MethodB(IComparable a) { //... } 

Do these two methods differ from each other in any way and have one of the advantages of any other? If so, what could be the scenario in which one of them is better to use?

Thank you so much!

+7
c #
source share
1 answer

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/*02000002*//TestStruct/*02000026*/ IL_0037: call void Tests.Program/*02000002*/::TestMethodNonGeneric(class Tests.Program/*02000002*//ITest/*02000025*/)/*06000002*/ IL_003c: nop 

Generic:

 IL_0059: ldloc.0 // ts IL_005a: call void Tests.Program/*02000002*/::TestMethodGeneric<valuetype Tests.Program/*02000002*//TestStruct/*02000026*/>(!!0/*valuetype Tests.Program*//*02000002*//*/TestStruct*//*02000026*//**/)/*06000001*/ 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.

+5
source share

All Articles