Search

Loading...

Sep 22, 2008

How to get Property list only of Derived class?

Hi All,

Recently I seen one requirement on ASP.Net Forum, some one posted question about How to get property list of Derived class.

Generally if we want to get all the property of class we use GetProperties() method. Which gives you the PropertyInfo[]. Lets see with example. We have following class Hierarchy.

class A
{
public int Id { get; set; }

public virtual void PrintMe()
{
Console.WriteLine("Id : " + Id);
}

}

class B : A
{
public string Name { get; set; }
public string Address { get; set; }
public override void PrintMe()
{
base.PrintMe();
Console.WriteLine("Name : " + Name);
}
}



In A there is only one property and in B we have 2 more property, our goal to get only two property declared in class B. Lets check with GetProperties().




PropertyInfo[] properties = typeof(B).GetProperties(); 


Console.WriteLine(properties.Count()); //will print 3



You can see its printing 3, that means it consider properties which are in parent and child too. There is one overload of GetProperties() which has BindingFlags, but with that also we are not achieving our goal.



So here is the solution using LINQ.




var prop =
from
p in typeof(B).GetProperties()
where p.DeclaringType == typeof(B)
select p;

Console.WriteLine(prop.Count()); //Will print 2



We are filtering on DeclaringType; which should be typeof(B). You can see now its returning 2, that what we needed.

1 comment:

donald said...

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Betty


http://www.my-foreclosures.info