I was recently working on a project where we needed a System.Type object based on settings in the application configuration file. It seems like a simple thing to do but there is a catch that I keep forgetting when using Type.GetType. When I tried to get the type for a SqlConnection I was a little surprised that it was null.
Type result = Type.GetType("System.Data.SqlClient.SqlConnection", false,true);
I tested a couple of custom classes in separate assemblies that were specific to the solution and they worked; this left me baffled and trying to remember when and where I had encountered this before (and more importantly the solution). Feeling like I was not making any progress I tried several other classes and started picking randomly on Exception classes like System.Data.SqlClient.SqlException, System.Configuration.ConfigurationException and System.ApplicationException. Both the Sql and Configuration Exception classes returned a null; but the ApplicationException returned a Type object…
Type result = Type.GetType("System.Data.SqlClient.SqlException", false,true);//null Type result = Type.GetType("System.Configuration.ConfigurationException", false,true);//null Type result = Type.GetType("System.Data.SqlClient.ApplicationException", false,true);//not null
That is when the ton of bricks hit me. Types in mscorlib and your projects custom assemblies will return from Type.GetType but for the assemblies that make up the .net framework you need the fully qualified name of the type.
In order to get the SqlException you need to use something like this
Type.GetType("System.Data.SqlClient.SqlException,System.data, version=188.8.131.52, Culture=neutral, PublicKeyToken=b77a5c561934e089",false,true);
The good news is the Culture and PublicKeyToken do not change for the .net framework assemblies*. The culture is always neutral and the PublicKeyToken has been b77a5c561934e089 since the frameworks release.
*MVC on the other hand…
System.Web.MVC, System.Web.Routing, System.Web.Abstractions (add a few other DLLs) have a PublicKeyToken of 31BF3856AD364E35
It makes sense that MVC would not be considered part of the .net framework and having a different PublicKeyToken. It just means we need to make sure we are using the correct PublicKeyToken and version numbers with the fully qualified names.