Converting a string to a class name

I have a string variable that represents the name of a custom class. Example:

string s = "Customer";

I will need to create an arraylist of customers. So, the syntax needed is:

List<Customer> cust = new .. 

How do I convert the string s to be able to create this arraylist on runtime?


Solution 1:

Well, for one thing ArrayList isn't generic... did you mean List<Customer>?

You can use Type.GetType(string) to get the Type object associated with a type by its name. If the assembly isn't either mscorlib or the currently executing type, you'll need to include the assembly name. Either way you'll need the namespace too.

Are you sure you really need a generic type? Generics mostly provide compile-time type safety, which clearly you won't have much of if you're finding the type at execution time. You may find it useful though...

Type elementType = Type.GetType("FullyQualifiedName.Of.Customer");
Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType });

object list = Activator.CreateInstance(listType);

If you need to do anything with that list, you may well need to do more generic reflection though... e.g. to call a generic method.

Solution 2:

This is a reflection question. You need to find the type then instantiate an instance of it, something like this:

Type hai = Type.GetType(classString,true);
Object o = (Activator.CreateInstance(hai));  //Or you could cast here if you already knew the type somehow

or, CreateInstance(assemblyName, className)

You will need to watch out for namespace/type clashes though, but that will do the trick for a simple scenario.

Also, wrap that in a try/catch! Activator.CreateInstance is scary!