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.
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.
You convert an Object variable to another data type by using a conversion keyword such as CType Function.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With