In resolving the question
Error Loading ASP.Net Profile
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
HashSet<T>
but not List<T>
?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 in mscorelib
, HashSet<T>
is not.
As per the documentation:
If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace
As for your second question, if you provide a qualified type name to an assembly that is not available in the current framework/profile, GetType
will 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):
If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and Mscorlib.dll, in that order. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. If the assembly has a strong name, a complete assembly name is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With