Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to a class name

Tags:

c#

.net

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?

like image 948
Bob Smith Avatar asked Jan 29 '09 21:01

Bob Smith


People also ask

Can we use string as a class name in Java?

String is already the name of a class. The String class. This, to me, assumes you want to override that class. @MichaelPickett Yea, String is already a class name, i know.

How do I convert a class name to a string?

Get Class Name Using class. In the GetClassName class, we use ExampleClass. class to get the information of the class. It returns a Class instance of type ExampleClass . Now we can call getSimpleName() using the classNameInstance that will return only the class name as a String.

How do I get the class of a string in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.


1 Answers

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.

like image 62
Jon Skeet Avatar answered Oct 04 '22 11:10

Jon Skeet