Creating Class Instances from Type Strings

If you’ve looked through the web.config or the machine.config then you’ve had to have seen various type strings strewn about the configuration.  But have you ever wondered how they use those type strings to actually make a useful class instance (or object instance if you prefer) out of that type string?  It’s actually really easy.

You only have to do two thing.  First, pass the type string to the Type.GetType method.  If you pass in a valid type string, the method will return type information for that type. If you pass in an invalid type string, the method returns null (though you can send in a boolean parameter to tell it to throw an error right there if you want). 

Second, pass the resulting type information into the Activator.CreateInstance method.  There are 13 overloads to the CreateInstance method, so you can also pass in constructor parameters (if needed) as well as a bunch of other information I’ve never really bothered to research.

Following is an example that shows how to create different database connection objects using type strings:

//Use must use an interface (or base class) to store a
//reference to the object you want to create because the
//exact object type varies based on which type string
//you use to create the object. In this example we are
//creating either a SqlDbConnection or an
//OleDbConnection, so we use an IDbConnection to store a
//reference to the object because both implement the
//IDbConnection interface.

Type cnxType; //stores reference to the object type
IDbConnection cnx; //stores reference to the object instance

//Example of creating a SqlConnection using a type string
cnxType = Type.GetType(@”System.Data.SqlClient.SqlConnection, System.Data,
     Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″);

cnx = (IDbConnection)Activator.CreateInstance(cnxType);

//Example of creating an OleDbConnection using a type string
cnxType = Type.GetType(@”System.Data.OleDb.OleDbConnection, System.Data,
     Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″);

cnx = (IDbConnection)Activator.CreateInstance(cnxType);

// … Do Something With Your Connection …