I have created the following class:
class GenericTest
{
public T Do<T>( T test ) where T : class
{
return test;
}
public IEnumerable<T> Do<T>( List<T> test ) where T : class
{
return test;
}
public IEnumerable<T> Do<T>( IEnumerable<T> test ) where T : class
{
return test;
}
}
This has three overloads of the Do() function. I'm trying to understand how the method parameter matching works in C# for generics, especially around interface parameters. So, I have the following test program:
static void Main( string[] args )
{
GenericTest testing = new GenericTest();
string s = "TEST";
List<string> list = new List<string> {s};
Stack<string> stack = new Stack<string>();
stack.Push( s );
testing.Do( s ); //calls public T Do<T>( T test )
testing.Do( list ); //calls IEnumerable<T> Do<T>( List<T> test )
testing.Do( stack ); //calls public T Do<T>( T test ) where T : class
}
The first call to Do() works as I expected, then the concrete class List parameter matches nicely against the List parameter method, but when I pass an IEnumerable, the compiler doesn't use the IEnumerable parameter method, instead it chooses the generic T method. Is this expected behaviour? Can I not overload with just an interface parameter in a generic?