Monday, February 21, 2011

How to get instances in all private fields of an object?

I would like to use reflection to investigate the private fields of an object as well as get the values in those fields but I am having difficult finding the syntax for it.

For example, an object has 6 private fields, my assumption is that I could fetch their FieldInfo with something like

myObject.GetType().GetFields(BindingFlags.NonPublic)

but no dice - the call returns an array of 0.

Whats the correct syntax to access fields?

From stackoverflow
  • BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static
    
    George Mauer : Ahh, its the Instance that I was missing
    leppie : Just added the static bit in case you needed that too :)
  • You should also add BindingFlags.Instance

    myObject.GetType().GetFields(BindingFlags.NonPublic|BindingFlags.Instance)
    
  • You've overridden the default flags, so you need to add Instance back in...

    myObject.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
    
    Meta-Knight : +1 for the explanation..
  • Since you want to retrieve both fields and values:

    from field in myObject.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
    select new
    {
        Field = field,
        Value = field.GetValue(myObject)
    };
    

0 comments:

Post a Comment