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?
IsSubclassOf. Which indicates that Derived is a subclass of Base , but that Base is (obviously) not a subclass of itself.
You would need to have the properties be declared as virtual on the base class and then override them in the derived class. You would either need to implement the property in the base class to return a default value (such as null) or to make it abstract and force all the derived classes to implement both properties.
Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
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);
}
...I want only those properties which are in child class. Is this possible?
You need to use the GetProperties overload that takes a BindingFlags argument and include the BindingFlags.DeclaredOnly
flag.
PropertyInfo[] infos = typeof(ChildClass).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
DeclaredOnly: Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With