Thursday, August 5, 2010

C#: How to dynamically get or set property values using reflection

Snippet for dynamically getting the value of a property using reflection:


var customer = new Customer();
customer.CustomerId = 3;

var id = customer.GetType().GetProperty("CustomerId").GetValue(customer, null);
// id is 3.

And to set the value of a property:


var customer = new Customer();

customer.GetType().GetProperty("CustomerId").SetValue(customer, 3, null);
// customer.CustomerId is now 3.