Search code examples
c#dynamicinstantiationactivatorobjectinstantiation

Dynamic Type instantiation C#


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


Solution

  • 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);