Frederik De Clercq
Frederik De Clercq

Reputation: 365

Generic extension methods using where T : Interface

Does these 2 extension methods are the same or is there some danger in using 1 of the 2

public static T  GetSomthingFromListOf<T>(this List<T> list)where T: IMyInterface
{
    //do somthing that returns an item of T
}

Versus

public static IMyInterface GetSomthingFromList(this List<IMyInterface> list)
{
    //do somthing that returns an item of IMyInterface
}

Upvotes: 2

Views: 202

Answers (2)

apocalypse
apocalypse

Reputation: 5884

In addition to @Clint answer:

1) if you have instance of List<ConcreteType> - only generic extension method will be available

2) if you pass struct as a parameter to non-generic method which expects interface - boxing will occur

Upvotes: 1

Clint
Clint

Reputation: 6220

The only real difference is in the return type, the first one will return the type itself and constrain it so that it has to implement IMyInterface, and the second will just return the IMyInterface instance.

The second is useful for when you just want to expose the interface's members; the first is good for when you need to return the original type, but make sure that you can treat it in the method as an IMyInterface.

Upvotes: 2

Related Questions