On Oct 3, 5:13 am, Peter Duniho <NpOeStPe...@NnOwSlPiAnMk.comwrote:
I believe the "'2" means "two type parameter" (It would be completely
legal to also have a SortedDictionary which take one or three type
parameters)
Thank you. You certainly saved this thread from my own wild
speculations, and your answer makes perfect sense (and in fact is borne
out in test code with varying numbers of generic parameters). :)
I find it interesting to see that the name of the type returned is
identical no matter what the generic parameter is. I guess that's
because there's just one copy of the compile generic implementation?
Type.ToString() *could* provide that information, but it would be a
little bit more expensive. Personally I think that the expensive would
be worth it, but there we go... You can do it by hand though. For
instance:
using System;
using System.IO;
using System.Collections.Generic;
public class Test
{
static void Main()
{
Type listOfString = new List<string>().GetType();
Type listOfInt = new List<int>().GetType();
ShowType(listOfString);
ShowType(listOfInt);
}
static void ShowType(Type t)
{
string name = t.FullName;
int tick = name.IndexOf('`');
if (tick != -1)
{
name = name.Substring(0, tick);
Type[] args = t.GetGenericArguments();
// So much easier with LINQ...
string[] argNames = new string[args.Length];
for (int i=0; i < args.Length; i++)
{
argNames[i] = args[i].Name;
}
name = string.Format("{0}<{1}>", name, string.Join(",",
argNames));
}
Console.WriteLine(name);
}
}
The type reference is obviously not the same, since the ToString()
result is different according to the actual concrete instance of the
generic class. But multiple references wind up with the same Name property.
Although the type references themselves aren't the same, if you call
GetGenericTypeDefinition() on both of them, *those* references will be
the same.
I love generics, but clearly I could use a little edumacation on the
topic. :)
Reflection on generics is somewhat messy, unfortunately. It's even
worse when a type which is "open" at compile-time is "closed" at
runtime...
I can't resist a plug at this point, I'm afraid: try the generics
chapter of my book and see if it helps. It's already available for
early access:
http://manning.com/skeet
Jon