Thursday, December 24, 2009

Devil’s in the details : typeof Generics C#

Been a while since I’ve posted but thought this tidbit was interesting.

Given the types:

class X {}
class Y<A>{}
class Z<A,B>{}

The following statements are legal:

var tx = typeof (X);             //simples
var ty1 = typeof (Y<int>);       //fine
var ty2 = typeof (Y<>);          //and again
var tz1 = typeof(Z<int, int>);   //easy enough

Interesting behaviour starts occurring when you working with generics based on multiple types:

var tz2 = typeof(Z<>);       //ruh-roh!!  Error: Using the generic type 'Z<A,B>' requires '2' type arguments
var tz3 = typeof(Z<int,>);   //Error: Type expected
var tz4 = typeof (Z<, int>); //Same again
var tz5 = typeof (Z<,>);     //Great success!


So it seems you either have specify ALL the types or NONE of the types, which made me wonder why the need to put the comma in tz5? Answer is because it is perfectly legal to have multiple types use the same class name e.g.

class Z {}
class Z<A> {}
class Z<A,B>  {}

Effectively the generic parameters (or lack thereof) are part the class signature.