0

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

Caracole
  • 13
  • 1
  • 5

2 Answers2

1

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);
gsharp
  • 27,557
  • 22
  • 88
  • 134
0

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);
Sean
  • 60,939
  • 11
  • 97
  • 136