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

Viewed 1897

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

I needed to get from the base class the derived class name and properties but nothing about the base class...

Based on the top answer I used the following... Hopefully it helps someone else!

public abstract class StorageObject
{
    protected readonly string TableName;
    protected readonly string[] ColumnNames;

    protected StorageObject()
    {
        TableName = GetType().Name;

        ColumnNames = GetType().GetProperties().Where(x => x.DeclaringType == GetType())
            .Select(x => x.Name)
            .ToArray();
    }
}

public class Symbol : StorageObject
{
    public string Name { get; private set; }
    public bool MarginEnabled { get; private set; }
    public bool SpotEnabled { get; private set; }
    public Symbol(ICommonSymbol symbol)
    {
        Name = symbol.CommonName;
        
        if (symbol is BitfinexSymbolDetails bsd)
        {
            MarginEnabled = bsd.Margin;
        }

        if (symbol is BinanceSymbol bs)
        {
            SpotEnabled = bs.IsSpotTradingAllowed;
            MarginEnabled = bs.IsMarginTradingAllowed;
        }
        
    }
}
Related