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
CodePudding user response:
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)