Sunday, August 29, 2004

Using System.Reflection to get at private fields in a class

6:41 In my unit testing binge I have come across the need (albeit a questionable one) to validate the contents of values internal to a class.

It took me a bit to figure out how to do this, so I figured I'd share it here.

The magic is in FieldInfo.GetValue (thanks to Stefan Goßner for pointing me in the right direction here.)

For instance, I have this:

    public class FlowManager

{
private OrderedDictionary<string, IBlock> m_Flows;

//... etc ...
}
I would get a reference to m_Flows like this (stripped down, but you get the idea):
    private OrderedDictionary<string, IBlock> GetFlows (

FlowManager flowManager)
{
FieldInfo field = fm.GetType ().GetField (
"m_Flows",
BindingFlags.NonPublic | BindingFlags.Instance);


if (field == null)
return null;

return field.GetValue (flowManager)
as
OrderedDictionary<string, IBlock>;
}

Updated: playing with formating to make the source look like source

No comments: