Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude properties of father class

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.

like image 676
Yahya Hussein Avatar asked Jan 02 '18 12:01

Yahya Hussein


2 Answers

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.

exclude inherited properties debug

Notice that with this solution you don't need to inspect the DeclaringType.

like image 83
rene Avatar answered Oct 19 '22 10:10

rene


Just try like this;

var childPropertiesOnly = typeof(Child)
         .GetProperties()
         .Where(x => x.DeclaringType != typeof(Father))
         .ToList();
like image 7
lucky Avatar answered Oct 19 '22 09:10

lucky