Converting a string to a class name

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.

Leave a Comment