Lance Ahlberg's WebLog

Reflection on reason

June 2004 - Posts

Reflecting on generic types

I've recently been having fun trying to get the type of a generic list using reflection.

The VS2005 MSDN doco suggests trying something like..

Type classType = Type.GetType(“System.Collections.Generic.List[[System.String,Mscorlib]],Mscorlib“,true);

I kept getting a a TypeLoadException : Could not load type 'System.Collections.Generic.List' from assembly mscorlib.

After a bit of deliberating, I decided to try the following..

System.Collections.Generic.List<String> stringList = new System.Collections.Generic.List<String>();

Type classType = stringList.GetType();

Console.WriteLine(classType.ToString());

Guess what I got...

System.Collections.Generic.List`1[System.String]

So what is this `1 about, it seems to be added to generic classes. 

From a bit more investigation it seems to represent the number of generic parameters (dimensions) associated with the class, so Dictionary is Dictionary`2.  While a generic class like MyGeneric<A,B,C,D,E> is actual MyGeneric`5.

 

More Posts