-2

How do I set my property value from array via reflection in C#?

public class Employee 
{
   public string Name { get; set; }    
   public int ID { get; set; }    
   public void SetValues(string[] items)
   {

   }
}

I need to use SetValues method to set property values from items array.

Bojan B
  • 2,091
  • 4
  • 18
  • 26

1 Answers1

0

Considering you said you Need to use SetValues(string[] items) {...}, and that you'd have an Employee object such as:

Employee emp = new Employee();

I believe you're looking for:

string[] values = new string[] {"someName", "someID"};
typeof(Employee).GetMethod("SetValues").Invoke(emp, new object[]{ values });

Now SetValues would have to convert (in its body) "someID" to int with something like:

ID = int.Parse(items[1]);
Mat
  • 1,440
  • 1
  • 18
  • 38