In resolving the question
I came across behavior of Type.GetType(string typeName) that I do not understand.
When getting the type of a List<int>, it is sufficient to specify the type as
System.Collections.Generic.List`1[[System.Int32]]
However, for HashSet<int>, I must specify a fully qualified type name like this
System.Collections.Generic.HashSet`1[[System.Int32]], System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
If I leave out any of the assembly, version, culture, or public key token, the type is not resolved.
Code to reproduce
// Returns expected type:
Type tListWorks =
Type.GetType("System.Collections.Generic.List`1[[System.Int32]]");
// Returns null:
Type tHashSetNull =
Type.GetType("System.Collections.Generic.HashSet`1[[System.Int32]]");
// Returns expected type:
Type tHashSetWorks =
Type.GetType("System.Collections.Generic.HashSet`1[[System.Int32]], System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
// Returns null (omitted Culture):
Type tHashSetNoCultureFails =
Type.GetType("System.Collections.Generic.HashSet`1[[System.Int32]], System.Core, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089");
Questions
- Why must I fully qualify
HashSet<T>but notList<T>? - Given that the Version qualification must be specified, what if the .NET Runtime is 3.5 (first one that had
HashSet<T>) or a later one such as .NET 4.5? What if the runtime is something else entirely like Silverlight or Mono?
List<T>is defined inmscorelib,HashSet<T>is not.As per the documentation:
As for your second question, if you provide a qualified type name to an assembly that is not available in the current framework/profile,
GetTypewill return null.The reason behind requiring all the assembly attributes is specified in the Type.GetType documentation (as pointed out by Jason Malinowski in the comments):