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?

1/6/2015 12:16:51 PM

Accepted Answer

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("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.

1/29/2009 9:27:55 PM

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow