Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between interface as type constraint and interface as parameter?

If I wanted to create a method that takes an instance of IList as a parameter (or any other interface, but let's use IList as an example), I could create a generic method with a type constraint, e.g.:

public static void Foo1<T>(T list) where T : IList
{

}

Alternatively, I could create a method that takes an IList parameter directly:

public static void Foo2(IList list)
{

}

For all intents and purposes, it seems like these methods behave exactly the same:

List<string> myList = new List<string>();
Foo1(myList);
Foo2(myList);

So here's my question -- what's the difference between these two approaches? It seems like the second approach is slightly more readable; are there any other differences I should be aware of (different IL being generated, etc)? Thanks in advance.

like image 894
Donut Avatar asked Oct 25 '11 13:10

Donut


2 Answers

A couple of differences:

  • If you ever need the real type again (e.g. to pass to another generic method or for logging) then the generic method will be better
  • T could be a value type and still end up being unboxed in the generic form. It's pretty unlikely that this would be the case for IList, but for other interfaces it's highly plausible
  • The generic form allows you to specify a concrete implementation type which is different from the actual object type. For example, you might pass in a null reference but still want to know which implementation type T is
  • They will be JITted differently; see Joe Duffy's recent blog post on generics for more information

It really depends on what you're doing of course... unless you actually need to know anything about T within the method, the only benefit to the generic form is the boxing point.

like image 81
Jon Skeet Avatar answered Sep 20 '22 20:09

Jon Skeet


if Foo2 returns void, it doesn't really matter. But suppose Foo2 returned a modified version of the list. With an IList parameter, the best it could do is return another IList. But with an IList constraint, it could return any type the caller wants assuming that type implements IList

like image 29
Robert Levy Avatar answered Sep 17 '22 20:09

Robert Levy