Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an object to a type based on the string value passed in C#

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.

like image 718
Anirban Kundu Avatar asked Jun 03 '11 17:06

Anirban Kundu


People also ask

How does convert ChangeType work?

The ChangeType() method returns an object of the specified type and whose value is equivalent to the specified object. Let's say we have a double type. Now, use the ChangeType method to change the type to integer. num = (int)Convert.

Which of the following is used to convert a number from one data type to another in Visual Studio?

You convert an Object variable to another data type by using a conversion keyword such as CType Function.


1 Answers

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.
like image 128
Jon Skeet Avatar answered Sep 29 '22 08:09

Jon Skeet