Sunday, November 28, 2010

C# - How to parse child properties through the parent class

Most of the times, we wanted to have a parent class that will contain all usable functions of the inheriting child classes, and thus a possibility that we might need to access custom properties of the inheriting classes. Since different class types can inherit the parent class, we need to use Reflection in order to gain access to the custom properties.

For instance this is your parent class:
class Parent
{
      public String Lastname { get; set; }
}
And this is your inheriting class:
class Child : Parent
{
     public String Name { get;  set; }
}
You wanted to have a common function on the parent class that will retrieve all custom properties of the inheriting classes. Then you will have this code:
class Parent
{
     public String Lastname { get; set; }

    public void GetChildProperties()
   {
         List<string> childProperties = new List<string>();
         Type childType = this.GetType().UnderlyingSystemType;
         PropertyInfo[] customProperties =  childType.GetProperties();
         foreach(PropertyInfo property in customProperties )
         {
            childProperties.Add(property.Name + " => " + property.Value);
         }
   }
}

No comments:

Post a Comment