Get by reflection properties of class ,but not from inherited class

C#Reflection

C# Problem Overview


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 :/

C# Solutions


Solution 1 - C#

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)

Solution 2 - C#

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);

Solution 3 - C#

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;

Solution 4 - C#

Add BindingFlags.DeclaredOnly

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnetmajorView Question on Stackoverflow
Solution 1 - C#Francesco BaruchelliView Answer on Stackoverflow
Solution 2 - C#Petar PetkovView Answer on Stackoverflow
Solution 3 - C#eran otzapView Answer on Stackoverflow
Solution 4 - C#TigranView Answer on Stackoverflow