Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if the property belongs to Base class or sub class dynamically in generic type using reflection?

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?

  1. Tried excluding it as mentioned in this question
  2. Tried determining whether the class is sub class or base class as mentioned here but that does not help either.
like image 412
Karan Desai Avatar asked Sep 13 '17 10:09

Karan Desai


People also ask

How do you check if a class is a subclass in C#?

IsSubclassOf. Which indicates that Derived is a subclass of Base , but that Base is (obviously) not a subclass of itself.

Can base class access derived class properties?

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.

What is a subclass in C#?

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.


2 Answers

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);
}
like image 159
tym32167 Avatar answered Sep 28 '22 09:09

tym32167


...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.

like image 38
TnTinMn Avatar answered Sep 28 '22 08:09

TnTinMn