5

I'm Unit Testing a class which has 2 private member variables inside of it. I have created a class which inherits from the class I am testing.

At first I just made the variables I wanted to access protected but I thought it would be cool if I could keep them private and use reflection to access them. I Googled and found various articles (& questions asked on here (http://stackoverflow.com/questions/4097682/c-sharp-use-reflection-to-get-a-private-member-variable-from-a-derived-class)) and the accepted answers did not work.

The linked SO question said:

// _commandCollection is an instance, private member
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;

// Retrieve a FieldInfo instance corresponding to the field
FieldInfo field = GetType().GetField("_commandCollection", flags);

// Retrieve the value of the field, and cast as necessary
IDbCommand[] cc =(IDbCommand[])field.GetValue(this);

However, there is no GetField() method. I tried a method that looked similar, GetRuntimeField() but that did not work.

My code (in the inheriting class) is:

public List<BaseData> RealAllData
{
    get
    {
        // Use reflection to access the private variable
        FieldInfo field = GetType().GetRuntimeField("mAllData");
        return (List<BaseData>)field.GetValue(this);
    }
}

If anyone knows why this does not work then I would be grateful. Thanks.

Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93
Luke
  • 560
  • 6
  • 26
  • 3
    Is this the area that [Reflection in the .NET Framework for Windows Store Apps](http://msdn.microsoft.com/en-us/library/hh535795.aspx) is all about, or is that something different? – AakashM Oct 15 '12 at 16:12
  • Yeah, that articles helped me get started. Thanks – Luke Oct 15 '12 at 17:06

1 Answers1

1

You can also put your reflection code into a Portable Class Library that targets .NET 4 and Windows Store apps. You'll then have access to the "old" reflection API, including BindingFlags, etc.

Claire Novotny
  • 1,593
  • 1
  • 15
  • 19