views:

375

answers:

1

I have a class like this:

class ItemList
{
    Int64 Count { get; set; }
}

and when I write this:

ItemList list = new ItemList ( );

Type type = list.GetType ( );
PropertyInfo [ ] props = type.GetProperties ( );

I get an empty array for props.

Why? Is it because GetProperties doesn't include automatic properties?

+9  A: 

The problem is that GetProperties will only return Public properties by default. In C#, members are not public by default (I believe they are internal). Try this instead

var props = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);

The BindingFlags enumeration is fairly flexible. The above combination will return all non-public instance properties on the type. What you likely want though is all instance properties regardless of accessibility. In that case try the following

var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var props = type.GetProperties(flags);
JaredPar
Thanks, didn't realise that. Also how are you able to provide multiple options for a single argument? Are BindingFlags bits that you shift?
Joan Venge
@Joan, yes. BindingFlags is an enumeration which uses bit flags you can manipulate with |. It's not providing multiple arguments, merely creating an enumeration value which has various bit combinations set.
JaredPar
Joan: Binding flags are a flags enum, so you can use | to pass multiple flags into the function.
Reed Copsey
Thanks Jared and Reed.
Joan Venge
For reference: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx
annakata
Thanks annakata.
Joan Venge