Welcome to Bangladesh Microsoft Technology Community Sign in | Join | Help

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. Couple of days back in this project that I am working I had to dynamically get/set  values from/to properties of object. The following code will give you a flavor of what I did.

To Get  value
===============

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

To Set  value
================

object myValue = "Something";
if (propertyInfo.CanWrite)
{
    this.propertyInfo.SetValue(myObject, myValue, null);
}

Published Sunday, November 19, 2006 9:28 AM by Shahed

Comments

No Comments

Anonymous comments are disabled