Saturday, November 14, 2009

Using Reflection to Get and Set values of Properties

The assembly that is generated for .Net Framework has metadata that describes the structure of the assembly and its classes. By using reflection we can investigate the structure of classes and the data that assembly holds dynamically at runtime.

You can dynamically get/set values from/to properties of object. #

Get value

foreach (PropertyInfo info in myObject.GetType().GetProperties())
if (info.CanRead)
object o = info.GetValue(myObject, null);

Set value

object myValue = "Any_Value";
if (info.CanWrite), myValue, null);

It's very helpful and easy to use. Isn't is ?

No comments: