Reputation: 13
I'm looking to instantiate an object at runtime having its type in a string but also it's value in a string. eg:
string myType = "System.Int32";
string myValue = "3";
I'm looking to create an instance of myType and cast/assign myValue into the instance i just created.
I've looked into Activator.CreateInstance :
object objectInstance = Activator.CreateInstance(Type.GetType(myType));
But i can't get to pass my value to my instance (could be anything : int16/32/64, double, bool, custom type...).
Thank you for your help
Upvotes: 0
Views: 241
Reputation: 62472
You need to get the type object and then use the Convert
class:
string myType = "System.Int32";
Type type=Type.GetType(myType)
string myValue = "3";
object convertedValue = Convert.ChangeType(myValue, type);
Upvotes: 0
Reputation: 27927
That only works on value types...
var t = Type.GetType("System.Int32");
object x = Activator.CreateInstance(t);
if (t.IsValueType)
x = Convert.ChangeType("2", t);
Upvotes: 1