Generics in .NET 2.0 provides the ability to create strongly-typed collections in C#. Unfortunately, C# currently does not support generics variance, which would allow inheritance of generic types.

For example, consider a list of strings and a list of objects:

List<string> strings = new List<string>();
strings.Add( "hello" );
strings.Add( "goodbye" );
List<object> objects = new List<object>();
objects.AddRange( strings );

The final line in the code above generates a compiler error. But why? Since the ‘string’ class derives from the ‘object’ class, one would expect List<string> to also implicitly derive from List<object>. This capability is called generics variance, but C# currently does not support it.

Fortunately, you can brute force your way to a solution by creating a generic ConvertIEnumerable method:

Read the rest of this entry »