Filling a Private Field on a Base Class Using Reflection

Ok here’s the next step in this testing kick. So now you have your test classes that create classes. Swell. Problem is, there are private fields on the base class of whatever class you are creating. So you’re screwed, right? Not really. Now what I am about to do is nothing new. It’s just basically using Reflection and FieldInfo to fill a field on a base class. Actually very easy. Here’s the code for the example.

using System;
using System.Collections.Generic;
using System.Reflection;

public class UserBase
{
  private Boolean _isBaseUser;

  public UserBase()
  {
      _isBaseUser = true;
  }

  public Boolean IsBaseUser
  {
      get
      {
          return _isBaseUser;
      }
  }
}

public class MainUser : UserBase
{
  //Simple list used to "cache" the field info so reflection doesn't have to be used
        //again for a type that has already been used.
  private static Dictionary<Type, List<FieldInfo>> typeToInfoList;

  /// <summary>
        /// This is used to fill in the needed field on the passed in object.  This is done by reflection/
        /// FieldInfo.  Basically you get the field info you want off the type, then you use the info to
        /// fill the field on the object.  
        /// </summary>
        /// <param name="objectToFill">This is the object that needs the field changed.</param>
        /// <param name="fieldName">This is the name of the field.</param>
        /// <param name="value">This is the value to be set.</param>
        /// <param name="typeToCheck">This is the type of the class that the field resides.</param>
  public static void FillField(Object objectToFill, String fieldName, Object value, Type typeToCheck)
  {
      List<FieldInfo> fieldInfoList;
      FieldInfo neededFieldInfo;
      Boolean heldInfoList;

      if (typeToInfoList == null)
      {
          typeToInfoList = new Dictionary<Type, List<FieldInfo>>();
      }
      //Check to see of the list already has the field info and save that 
          //boolean for later use.
      heldInfoList = typeToInfoList.ContainsKey(typeToCheck);
      //If it is in the "cache", grab it.  If not, create a new list
          //for the passed in type.
      fieldInfoList = heldInfoList ? typeToInfoList[typeToCheck] : new List<FieldInfo>(typeToCheck.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));

     //Now just look for the needed field info in the list. 
     neededFieldInfo = fieldInfoList.Find(currentItem => currentItem.Name == fieldName);
      //Use the field info to set the value on the object.
      neededFieldInfo.SetValue(objectToFill, value);

      //Store the field info list if it isn't being stored already.
      if (!heldInfoList)
      {
          typeToInfoList.Add(typeToCheck, fieldInfoList);
      }
  }

  //Simple constructor to create the user.
  public static MainUser Create()
  {
      MainUser testUser;

      testUser = new MainUser();

      return testUser;
  }
}

That’s pretty much it. What the hell is all that? Well basically you have the UserBase as the base class for the example. MainUser that in inherits UserBase. The FillField method that does all the work. And lastly, the dictionary used as a lame cache for this example. Why cache anything? Well everything you get the field info, reflection is used. This can be expensive. So why bother getting the same field info for the same type every time this method is called? Just store it somewhere so that if the same class type is passed through again, you can easily access the field info for the class without going for reflection again.

Here’s an example of the use:

using Microsoft.VisualStudio.TestTools.UnitTesting;

 [TestClass]
 public class FillFieldTest
 {
     [TestMethod]
     public void FillField_CheckFieldForChange()
     {
         MainUser testUser;

         testUser = new MainUser();
         Assert.IsTrue(testUser.IsBaseUser);

         MainUser.FillField(testUser, "_isBaseUser", false, typeof(UserBase));
         Assert.IsFalse(testUser.IsBaseUser);

         MainUser.FillField(testUser, "_isBaseUser", true, typeof(UserBase));
         Assert.IsTrue(testUser.IsBaseUser);
     }
 }

First test is checking to see if the IsBaseUser property is true. This will be true since UserBase sets _isBaseUser to true on instantiation.

Second test is checking to see if the FillField method worked correctly.

Third test is really just to step through a second time so you can see how the quasi-caching works.