I have following two classes (models), one is base class and other is sub class:
public class BaseClass { public string BaseProperty{get;set;} } public class ChildClass: BaseClass { public string ChildProperty{get;set;} }
In application I am calling ChildClass
dynamically using generics
List<string> propertyNames=new List<string>(); foreach (PropertyInfo info in typeof(T).GetProperties()) { propertyNames.Add(info.Name); }
Here, in propertyNames
list, I am getting property for BaseClass
as well. I want only those properties which are in child class. Is this possible?
What I tried?
- Tried excluding it as mentioned in this question
- Tried determining whether the class is sub class or base class as mentioned here but that does not help either.
Answer
You can try this
foreach (PropertyInfo info in typeof(T).GetProperties() .Where(x=>x.DeclaringType == typeof(T))) // filtering by declaring type { propertyNames.Add(info.Name); }