3

I have a simple POCO class, e.g.

class C {
  [MyAtrib]
  public int i {get; set;}
  [MyAtrib]  
  public int i2;
}

When I call:

GetType().GetFields(
  BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

on that class (instance) I can't get the FieldInfo for those members that have automatically generated getters/setters (i.e. int i above).

Actually, I'm trying to read those custom attributes (MyAtrib) and can't do it for those properties that have {get; set;}.

Why is that? I'd expect to get both i and it's (private) backing field, since i is public.

Can I get to i's MyAtrib somehow through reflection?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
igorludi
  • 1,519
  • 2
  • 18
  • 31
  • 3
    Those with getters and setters are not fields; they are properties. – Austin Salonen Oct 16 '13 at 17:38
  • You definitely get the backing field, using BindingFlags.NonPublic is sufficient. It has an unspeakable name, `k__BackingField`. The attribute is *not* applied to the backing field, it exists on the property. Calling GetProperty() is required to retrieve it. – Hans Passant Oct 16 '13 at 18:44

1 Answers1

9

You get fields right now, but public int i {get; set;} is a property. You need to get properties:

// note: properties -> generally public
GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116