0

In c# I have a class with properties on it.

public class MyClass
{
   public MyPropClass1 Prop1 { get; set; }
   public MyPropClass2 Prop2 { get; set; }
   public AnotherClassAltogether Prop3 {get; set; }
}

Lets say MyPropClass1 and MyPropClass2 both inherit from MyPropBaseClass but AnotherClassAltogether doesn't.

What is the simplest way to get all properties from MyClass which either are, or somewhere down the chain are inherited from, a class?

E.g. if I wanted to query MyClass for properties based on MyPropBaseClass then it should return Prop1 and Prop2

Jonny
  • 796
  • 2
  • 10
  • 23

1 Answers1

2

You need to get all properties and then use PropertyInfo.PropertyType to find those which inherit from target type, you can use Type.IsAssignableTo for that:

var props = typeof(MyClass)
    .GetProperties()
    .Where(pi => pi.PropertyType.IsAssignableTo(typeof(MyPropBaseClass)))
    .ToList();

IsAssignableTo is available since .NET 5 so for earlier versions use IsAssignableFrom: typeof(MyBase).IsAssignableFrom(pi.PropertyType)

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Perfect - by the way I have just asked a very similar question just with IEnumerables here https://stackoverflow.com/questions/69699228/how-to-get-properties-of-a-class-which-are-ienumerable-of-a-class-or-an-ienumera - this might be the same answer. – Jonny Oct 24 '21 at 17:55
  • @Jonny was glad to help! For the `IEnumerable` one - I've added a duplicate which wil help you to find enumerables. Possibly you will need adjust it a little bit - if you need exactly `IEnumerables` - check for generic type and generic type defenition being `IEnemerable<>` – Guru Stron Oct 24 '21 at 19:50