Search code examples
c#reflection

Get Non-Inherited Properties


I'm trying to read all of the properties of a given object, reading in only those that are declared on the object's type, excluding those that are inherited. IE:

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

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

And so I want to only get B back. Reading the docs, I assumed below was what I needed, but that actually returned nothing at all.

var names = InstanceOfChild.GetType().GetProperties(BindingFlags.DeclaredOnly).Select(pi => pi.Name).ToList();

Solution

  • Just need a couple other BindingFlags

    var names = InstanceOfChild.GetType().GetProperties(
       BindingFlags.DeclaredOnly |
       BindingFlags.Public |  
       BindingFlags.Instance).Select(pi => pi.Name).ToList();