Interface constraint on generic method arguments

c#, generics

Solution

In your specific example there is no difference. But take the following method:

public static class Class1
{
    public static T Test1<T>(T arg1) where T : IFoo
    {
        arg1.Bar();
        return arg1;
    }

    public static IFoo Test2(IFoo arg1)
    {
        arg1.Bar();
        return arg1;
    }
}

`Test1` will return the specific type of arg1, whereas `Test2` will only return the interface. This is often used in fluent interfaces.

Extended example:

public interface IFoo
{
    void Bar();
}

public class Foo : IFoo
{
    // implementation of interface method
    public void Bar()
    {
    }

    // not contained in interface
    public void FooBar()
    {
    }
}


var foo = new Foo();
Class1.Test1(foo).FooBar(); // <- valid
Class1.Test2(foo).FooBar(); // <- invalid

Problem

In my quest to understand C# properly, I find myself asking what are the practical differences between specifying an interface constraint on a generic method argument, and simply specifying the interface as the type of the argument? ``` public interface IFoo { void Bar(); } public static class Class1 { public static void Test1<T> (T arg1) where T : IFoo { arg1.Bar(); } public static void Test2(IFoo arg1) { arg1.Bar(); } } ``` EDIT I know my example is very narrow as it's just an example. I'm quite interested in differences that go outside its scope.

Original source

Related problems