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);
}

This article is part of the GWB Archives. Original Author: Shahed Khan

New on Geeks with Blogs