55

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
  • John, there is no generic implementation of the ArrayList class in the .NET framework. Bob, this is out of scope for the question, but if you're programming in C# 2.0+, you should substitute the ArrayList for something generic.
    – senfo
    Commented Jan 29, 2009 at 23:12

2 Answers 2

79

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.

0
29

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.