views:

502

answers:

3

Hi,

If I use

sometype.GetProperties();

I get all of the properties from the type and it's parent. However I only want to retrieve the properties defined explicitly in this type (not the parents). I though that was what the BindingFlags.DeclaredOnly option was for. However, when I try this:

sometype.GetProperties(BindingFlags.DeclaredOnly);

...I get 0 properties.

Anyone know what I am doing wrong?

Thanks!

+4  A: 

According to Microsoft:

  • You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
  • Specify BindingFlags.Public to include public methods in the search.
  • Specify BindingFlags.NonPublic to include non-public methods (that is, private, internal, and protected methods) in the search. Only protected and internal methods on base classes are returned; private methods on base classes are not returned.
  • Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.
Groo
So to point this out: *without* any BindingFlags, there are some defaults. Do you know which they are?
Stefan Steinegger
If you use the `GetProperties()` overload (without parameters), you will get all public properties.But `GetProperties(BindingFlags.Default)` will return an empty array.
Groo
Heh, so what's the use of BindingFlags.Default?! ;)
UpTheCreek
It's recommended that all enums marked with a Flags attribute have a defined enum value for `0`. Since the underlying type for the enums flags is int, you must have an enum which represents the default value of int. You are likely to get a 0 value when you are instantiating it or doing bitwise operations with the flags.
Groo
+6  A: 

You need to expand your BindingsFlag a bit. They need to at least include what accessibility and instance vs. static in order to get anything meaningful back.

I think what you are actually looking for is the following

var flags = BindingFlags.DeclaredOnly 
  | BindingFlags.Intstance
  | BindingFlags.Public;
someType.GetProperties(flags);
JaredPar
+2  A: 

If you specify any BindingFlags, then you need to specify explicitly what you want properties you want to get. For example:

sometype.GetProperties (BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
Pete