5

After successfully getting a list of specific types out of an assembly using reflection, I now want to get at the public properties of each of those.

Each of these types derives from at least one base class.

I notice when I get properties on a type that I get properties from the base classes as well.

I need a way to filter out base class properties and only get back the properties for the type that I am calling get properties on.

I reckon it would be similar to how I'm only getting sub classes of a base type, excluding the base type, from a given base type.

Assembly.GetAssembly(baseType).GetTypes().Where(type => type.IsSubclassOf(baseType)).ToList()
starblue
  • 55,348
  • 14
  • 97
  • 151
topwik
  • 3,487
  • 8
  • 41
  • 65

2 Answers2

11

Use BindingFlags.DeclaredOnly in your call to Type.GetProperties:

var properties = Type.GetProperties(BindingFlags.DeclaredOnly | 
                                    BindingFlags.Public |
                                    BindingFlags.Instance);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @towps- see here to read more about it: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx – RichardOD Aug 18 '09 at 14:39
  • Thanks folks! I wasn't sure why only attaching the DeclaredOnly flag wasn't getting me anything. Seems you require public and instance? DeclareOnly and Public still didn't get me anything. – topwik Aug 18 '09 at 15:46
  • Yes, you've got to specify Public or NonPublic, and Static or Instance (or combinations). – Jon Skeet Aug 18 '09 at 16:03
2

use the binding flag BindingFlags.DeclaredOnly in the GetProperties method

Gregoire
  • 24,219
  • 6
  • 46
  • 73