Practical advantage of generics vs interfaces

Asik picture Asik · Aug 29, 2011 · Viewed 11.4k times · Source

What would be a practical advantage of using generics vs interfaces in this case:

void MyMethod(IFoo f) 
{
}

void MyMethod<T>(T f) : where T : IFoo
{
}

I.e. what can you do in MyMethod<T> that you couldn't in the non-generic version? I'm looking for a practical example, I know what the theoretical differences are.

I know that in MyMethod<T>, T will be the concrete type, but nonetheless I will only be able to use it as an IFoo within the body of the method. So what would be a real advantage?

Answer

Thomas Levesque picture Thomas Levesque · Aug 29, 2011
  • Calling a method through an interface is slower than calling it directly on the concrete type
  • If the type implementing IFoo is a value type, the non-generic version will box the value of the parameter, and boxing can negatively affect performance (especially if you call this method very often)
  • If your method returns a value, the generic version can return a T rather than a IFoo, which is convenient if you need to call a method of T on the result