Suppose I have the following two classes.
public class Father
{
public int Id { get; set; }
public int Price { get; set; }
}
public class Child: Father
{
public string Name { get; set; }
}
How can I know if a specific property is a Father property (Inherited) or a Child property?
I tried
var childProperties = typeof(Child).GetProperties().Except(typeof(Father).GetProperties());
but seems like Except is not detecting the equality of Father properties and Child inherited properties.
Use the overload on GetProperties that accepts BindingFlags. Include the DeclaredOnly flag next to the Public and Instance flags and you're all set:
var childProperties = typeof(Child)
.GetProperties(
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly // to search only the properties declared on
// the Type, not properties that
// were simply inherited.
);
This will return one property, the Name.

Notice that with this solution you don't need to inspect the DeclaringType.
Just try like this;
var childPropertiesOnly = typeof(Child)
.GetProperties()
.Where(x => x.DeclaringType != typeof(Father))
.ToList();
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