2

Possible Duplicate:
Find a private field with Reflection?

I am trying to display a class's field names using the System.Reflection.GetFields() method.

Problem is it only works when the fields are declared as "public". For example :

class Element
{
    private String id;
    private string a;
    private string b;
    private int c;
    private Dictionary<String, String> dict;

    public Element(String id)
    {
        this.id= id;
    }}

When I try calling the System.Reflection.GetFields() method, it doesn't work (it returns an empty array). However, if I change the visibility of the fields to "public", it works..

Anyone know how I can get it to work without having to make it public?

Thanks

Community
  • 1
  • 1

3 Answers3

3

Try this:

GetFields(BindingFlags.NonPublic | BindingFlags.Instance)

UPDATE: Here is what going under scene when you call GetFields without parameter:

public FieldInfo[] GetFields()
{
   return this.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
}

So, as you can see, private fields are not returned by default.

Btw here is description of GetFields() method from msdn:

Returns all the public fields of the current Type. Return Value: An array of FieldInfo objects representing all the public fields defined for the current Type. -or- An empty array of type FieldInfo, if no public fields are defined for the current Type.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
2

Try this

var fieldinfo = typeof(Element).GetField("field name", BindingFlags.NonPublic |
                             BindingFlags.Instance);
Flowerking
  • 2,551
  • 1
  • 20
  • 30
1

The GetFields method returns only the public fields. If you want it to return both private and public fields use this:

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

You must specify BindingFlags.Instance or BindingFlags.Static along with BindingFlags.Public or BindingFlags.NonPublic or no members will be returned.

Take a look at msdn for more information: MSDN

Storm
  • 684
  • 9
  • 20