About

I am a software developer in Seattle, building a new AI software company.

Ads

April 2009

Sun Mon Tue Wed Thu Fri Sat
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

Categories

Ads


« Hobbyist Programmers | Main | Shareware Industry Conference »

May 25, 2005

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.

 

Comments

where T: struct is published in MSDN, including the bit about not allowing nullable types:

http://msdn2.microsoft.com/library/d5x73970(en-us,vs.80).aspx

Fwiw, the <> syntax /is/ covered in the C# 2.0 spec...

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment