views:

134

answers:

4

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?

+4  A: 
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static
leppie
Ahh, its the Instance that I was missing
George Mauer
Just added the static bit in case you needed that too :)
leppie
+1  A: 

You should also add BindingFlags.Instance

myObject.GetType().GetFields(BindingFlags.NonPublic|BindingFlags.Instance)
Philippe Leybaert
+3  A: 

You've overridden the default flags, so you need to add Instance back in...

myObject.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
Greg Beech
+1 for the explanation..
Meta-Knight
A: 

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)
};
Bryan Watts