Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Interface to a Generic method parameter VS Implementing Interface to an method argument

Tags:

c#

.net

Im quite confused by what i found in a programming course.

In brief - I found a method which has that construction:

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

And as far as i know - the same exact effect we can can achive using just this:

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

Are those two ways differ from each other somehow and has one of them any advantage over the other? If so, how could look a scenario where one of them is better to use?

Thanks a lot!

like image 575
Jacek Dziurdzikowski Avatar asked Feb 02 '17 07:02

Jacek Dziurdzikowski


1 Answers

I was curious so I made a little testcode 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 resulting IL code:

Non-generic:

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, in the generic version, the specific type is used and therefor no boxing occurs.
In the non-generic version, the struct value has to be casted to ITest and so it gets boxed. So the generic version has a (very tiny) performance advantage.

Just my two cents, there maybe other more or less important differences in the two approaches.

like image 104
René Vogt Avatar answered Oct 17 '22 07:10

René Vogt