6

I have a requirement where the object type [name of the object] is passed as a string variable. Now based on the object name passed, I need to create that object type. Please note the string value contains the exact object type name. I have written a code snippet but it is throwing an exception.

e.g -

string objectName = "EntityTest.Entity.OrderEntity";//Entity type name object obj = new object(); object newobj = new object(); newobj = Convert.ChangeType(obj, Type.GetType(objectName)); 

I do this I get error -- > Object must implement IConvertible.

My entity OrderEntity has already implemented the IConvertible interface.

Any help/suggestion is greatly appreciated. Is there any other way I can create the object to fulfill my requirement.

2 Answers 2

10

You're currently trying to convert an existing object, rather than creating one of the right type. Assuming your Type.GetType call is working, you can just use:

Type type = Type.GetType(objectName); object x = Activator.CreateInstance(type); 

A few points to note:

  • Type.GetType(string) requires an assembly-qualified name unless the type is either in the currently-executing assembly or mscorlib
  • Activator.CreateInstance(Type) will call the parameterless constructor (which has to be accessible); if you need to pass arguments to the constructor, there are other overloads available.
Sign up to request clarification or add additional context in comments.

2 Comments

this is great but then how we can pass value into new generated object?
@HamedZakeryMiab: Do you mean you want to call a parameterized constructor? You could either call type.GetConstructors(), find the right constructor and invoke it, or use one of the overloads for Activator.CreateInstance that allows you to specify arguments. Try those, and if you run into problems, start a new question.
3

Your problem is that you're creating an instance of object and then trying to cast that to a more specific type (which it can't be).

You need a way to call the default constructor of the type that you're trying to create. Take a look at Activator.CreateInstance():

var type = Type.GetType(typeName); var instance = Activator.CreateInstance(type); 

If the type has no default constructor, the above example will fail. In that case, your best bet is probably to use this overload (that takes an array of objects to use as constructor parameters and then tries to find the best match)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.