Wednesday, September 1, 2010

C# Dynamically get and set values of a property from string


This sample code will let you retrieve the list of properties of an object and will also let you assign and get values dynamically given a property name as string.

Don't forget to include the System.Reflection namespace:

using System.Reflection;

MyClass myObject = new MyClass();
String objectValue;
String objectName;

//get properties
foreach(PropertyInfo info in myObject .GetType().GetProperties())
{
      objectName = info.Name;
      // get value
     if(info.CanRead)
         objectValue = info.GetValue(myObject,null);

     //set value
     objectValue = "Hello Pilipinas!";
     if(info.CanWrite)
       info.SetValue(myObject,objectValue,null);
}


Or you can access the property directly given it's name as string

PropertyInfo info = myObject.GetType().GetProperty("myPropertyName");

// get value
if(info.CanRead)
     objectValue = info.GetValue(myObject,null);


//set value
objectValue = "Hello Pilipinas!";
if(info.CanWrite)
    info.SetValue(myObject,objectValue,null);


No comments:

Post a Comment