Type.GetType (), HashSet <T> and assembly
When resolving the issue
I came across Type.GetType (string typeName) behavior that I don't understand.
When receiving the type List<int>
enough to specify the type as
System.Collections.Generic.List`1 [[System.Int32]]
However, for a HashSet<int>
I have to 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 any token of the assembly, version, culture or public key, the type will not be allowed.
Code to play
// 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 should I fully qualify
HashSet<T>
, but notList<T>
? - Given that you need to specify the version qualification, what if the .NET Runtime is 3.5 (the first of which has a
HashSet<T>
) or later, such as .NET 4.5? What if the runtime is something completely different than Silverlight or Mono?
List<T>
defined in mscorelib
, HashSet<T>
not .
According to the documentation :
If the type is in the current executable assembly or in Mscorlib.dll, it is enough to specify the type name assigned by its namespace
As for your second question, if you provided a qualified type name for an assembly that is not available in the current structure / profile, GetType
will return null.
A reason requiring all assembly attributes is listed in the Type.GetType documentation (as indicated by Jason Malinowski in the comments):
If typeName contains a namespace but not the assembly name, this method searches only the assembly of the calling object and Mscorlib.dll in that order. If typeName is fully qualified with an incomplete or fully qualified assembly name, this method searches the specified assembly. If the assembly has a strong name, the fully qualified name of the assembly is required.