I need to get and set a property value dynamically
I read this Get property value from string using reflection in C#
and did a below code for getting a value
public Object GetPropValue(Object obj, String name) {
foreach (String part in name.Split('.')) {
if (obj == null) { return null; }
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
Now i need to set the value to other object which has a same property name
Employee emp1=new Employee();
var city=GetPropValue(emp1, "Address.City");
Need to set this city to other employee. Here Address is other class
emp1.GetType().GetProperty("Address.City").SetValue(emp2,city,null) //always sets null
But it is not setting. How can i make a generic setter method to make this job simple?