96
class Parent {
   public string A { get; set; }
}

class Child : Parent {
   public string B { get; set; }
}

I need to get only property B, without property A but

Child.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)

return both properties :/

4 Answers 4

186

You should add BindingFlags.DeclaredOnly to your flags, i.e:

typeof(Child).GetProperties(System.Reflection.BindingFlags.Public
    | System.Reflection.BindingFlags.Instance
    | System.Reflection.BindingFlags.DeclaredOnly)
1
  • 2
    Can this the other way arround. Parent.GetProperties() and get all properties from the parent and child if the specific object is inherited by the child Feb 5, 2016 at 11:45
12

Try using the DeclaredOnly binding flag. It should limit the properties returned to only those declared on the class you are interested in. And here is a code sample:

PropertyInfo[] properties = typeof(Child).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
1
  • This worked nicely. I had to included Instance here to get the props, I tried first BindingFlags.Public | BindingFlags.DeclaredOnly and could not understand why I got empty results. Apr 28, 2021 at 9:31
6

From Type.cs : In this case use the DeclaredOnlyLookup

  private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
  internal const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
1
  • 1
    Interesting, I'll use this approach and define my own const BindingFlags. +1 for looking into the source code.
    – C. Tewalt
    Feb 18, 2016 at 17:50
4

Add BindingFlags.DeclaredOnly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.