how to populate an instance created by Activator.CreateInstance() method

1.5k views Asked by At
class Program
{
    static void Main()
    {
        testclass tc = new testclass();
        Type tt = tc.GetType();
        Object testclassInstance = Activator.CreateInstance(tt);

        PropertyInfo prop = tt.GetProperty("name");

        MethodInfo MethodName = tt.GetMethod("set_" + prop.Name);
        string[] parameters = new string[2];

        parameters[0] = "first name of the bla bla";

        MethodName.Invoke(testclassInstance, parameters);

        Console.WriteLine(testclassInstance.GetType().GetProperty("name").GetValue(testclassInstance, null));

        Console.ReadLine();
    }
}

class testclass
{
    public string name { get; set; }
}

output error message is:

Parameter count mismatch

i don't want to create constructor for testclass and pass parameters/populate like that. i want to populate its properties one by one.

plz link other useful instance populating methods. i know this is the silliest one.

2

There are 2 answers

2
Vsevolod Goloviznin On BEST ANSWER

Check out this question: how to create an instance of class and set properties from a Bag object like session

Type myType = Type.GetType(className);
var instance = System.Activator.CreateInstance(myType);
PropertyInfo[] properties = myType.GetProperties();

foreach (var property in properties)
{
    if (property.CanWrite) 
    {
        property.SetValue(instance, session[property.Name], null);
    }
}
0
Konrad Kokosa On

It is as easy as:

prop.SetValue(testclassInstance, "first name of the bla bla");