Open Generic Types
This is an undocumented feature of C#, not mentioned in any published article or in the current draft of the C#2.0 specification. It was recently revealed in one of Microsoft’s developer newsgroups by a developer in the C# team.
To refer to an open generic type, one simply uses an empty parameter list < >. If there are multiple parameters, then additional commas are necessary to identify the proper type, since generic types of the same name are disambiguated by the number of type parameters it contains.
Type type = typeof( System.Collections.Generic.List< > );
To bind the open type into a closed generic type, a call to type.MakeGenericType(types) is necessary.
Previously, I dynamically constructed a closed generic type from another one based on another type. In that instance, I need to find out if an arbitrary, type T, implemented the generic interface IComparable<T>. Not having (or, more accurately, knowing) a way to specify open types, I used a specific closed type, IComparable<string>. I don’t recall if it was necessary to make an intermediate call to GetGenericTypeDefinition before calling MakeGenericType.
Here’s another unpublished secret of the CLR:
Generics types can specify a struct or class constraint using “where T : struct” to restrict the type parameter to be a value type or reference type. The struct constraint actually is a bit more restrictive and prevents nullable types from being passed as well. The only type in the framework that currently uses this constraint is System.Nullable<T>, which apparently was the impetus for this constraint.