0

Following this answer, I'm trying to replicate it and iterate over my CustomerModel properties.

CustomerModel pippo = new CustomerModel();
Type customer = pippo.GetType();
FieldInfo[] fields = customer.GetFields(BindingFlags.Public | BindingFlags.Instance);

When using the debugger, fields always has a count = 0 but CustomerModel has a lot of public properties I'd like to see in fields. How can I do that? Here's an extract of some properties declared I'd like to see.

    [DataMember]
    public String Id { get; set; }

    [DataMember]
    public String LoginName { get; set; }

    [DataMember]
    public String Password { get; set; }

    [DataMember]
    public String CreationDate { get; set; }

Perhaps the binding flags are incorrect? I'm new to the use of reflection.

Community
  • 1
  • 1
Saturnix
  • 10,130
  • 17
  • 64
  • 120
  • I'd recommend changing the variable name from `customer` to `customerType` or something like that. `customer` sounds more like an instance of `CustomerModel`, rather than its type. – Joe Enos Jul 25 '13 at 15:58
  • yeah, I won't even store the variable anymore but just get the properties... This was just for testing purpose. – Saturnix Jul 25 '13 at 15:59

2 Answers2

6

Those are properties, not fields. Use GetProperties instead of GetFields.

In C#:

public class Foo {

    // this is a field:
    private string _name;

    // this is a property:
    public string Name { get; set; }

    // this is also a property:
    public string SomethingElse { get { return _name; } set { _name = value; } }

}
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • It's working! Thanks a lot and forgive the stupid question but this is really the first time I use reflections... Thanks again! :) – Saturnix Jul 25 '13 at 15:58
  • No problem. As you get more and more into reflection, you'll find all kinds of cool stuff you can do with it (and a lot of dangerous stuff too :)) – Joe Enos Jul 25 '13 at 15:59
2

As Joe correctly pointed out the members in question are properties not fields. These are auto-implemented properties and the compiler will generate backing fields for them. However these fields won't be public hence the GetFields call fails because it is looking for the public members only. If you want to see the generated fields then change the code to the following

FieldInfo[] fields = customer.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • +1 I'm not interested right now into retrieving private fields, but this is something new I've just learned - thanks for posting! – Saturnix Jul 25 '13 at 16:10