Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetType(), HashSet<T> and Assembly Qualification

Tags:

.net

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

  • Why must I fully qualify HashSet<T> but not List<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?
like image 928
Eric J. Avatar asked Jul 27 '12 05:07

Eric J.


1 Answers

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.

like image 131
Richard Szalay Avatar answered Oct 27 '22 03:10

Richard Szalay