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.

2
  • 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. Commented Jul 25, 2013 at 15:58
  • yeah, I won't even store the variable anymore but just get the properties... This was just for testing purpose. Commented Jul 25, 2013 at 15:59

2 Answers 2

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; } }

}
Sign up to request clarification or add additional context in comments.

2 Comments

It's working! Thanks a lot and forgive the stupid question but this is really the first time I use reflections... Thanks again! :)
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 :))
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);

1 Comment

+1 I'm not interested right now into retrieving private fields, but this is something new I've just learned - thanks for posting!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.