2
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.

Falko
  • 17,076
  • 13
  • 60
  • 105
Vaas
  • 43
  • 5
  • What exactly are you trying to do? Why didn't you do the simple thing and use [prop.SetValue(testclassInstance, "your string")](http://msdn.microsoft.com/en-us/library/hh194291%28v=vs.110%29.aspx)? – slugster Nov 27 '14 at 21:34
  • 1
    Your parameter array is too big: `string[] parameters = new string[1];` will fix it. – DavidG Nov 27 '14 at 21:36
  • It looks like search engine you are using have trouble finding good content. Try Bing - http://www.bing.com/search?q=c%23+set+property+reflection or Google - https://www.google.com/?q=c%23+set+property+reflection - both give linked duplicate as top suggestion. – Alexei Levenkov Nov 27 '14 at 21:39

2 Answers2

3

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);
    }
}
Community
  • 1
  • 1
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
0

It is as easy as:

prop.SetValue(testclassInstance, "first name of the bla bla");
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58