Sunday, November 28, 2010

C# - Get child properties

On my previous post, we talked about parsing child properties. We will use that piece of code to create an extension method for type Object and easily retrieve the child properties from any class.

For instance you have this parent class:
class Parent
{
      public String Lastname  { get; set; }
}
And you have this child class:

class Child : Parent
{
      public String Petname{ get; set; }
}


You can retrieve the child properties thru this:
class Parent
{
      public String Lastname  { get; set; }
    
     public void DoSomething()
     {
           PropertyInfo[] childProperties = this.GetChildProperties();
Object propertyValue = this.GetChildProperty("Petname");
     }
}
Here's how we define our extension method.

namespace CtrlAltDelete.Library.Helpers.Dynamic
{
    public static class ObjectExtensions
    {
         public static PropertyInfo[] GetChildProperties(this Object source)
        {
            return source.GetType().UnderlyingSystemType.GetProperties();
         }
         public static Object GetChildProperty(this Object source, String propertyName)
        {
            Type childType = source.GetType().UnderlyingSystemType;
            PropertyInfo property = childType .GetProperty(propertyName);
            if (property.CanRead)
                return property.GetValue(source, null);
            return null;
            }
    }
}

No comments:

Post a Comment