C# Get and Set Private fields using Reflection

In C#, we can use reflection to dynamically access private fields from an object. It is especially useful for Unit Testing your code, when you need to check private fields and members, or perform some set-up.

Now I don’t recommend doing this in your prod code, since in most cases, there’s a reason a field is set to private, in order to guarantee access security.

So how do we go about using reflection in C#? In my case, I created a helper class that my Unit Tests use to access private fields. Here is a quick snippet of what that class might look like:

using System.Reflection;

public class FieldAccessHelper
{
    public static object GetField<T>(T obj, string field)
    {
        return typeof(T).GetField(field, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
    }

    public static void SetField<T>(T obj, string field, object value)
    {
        typeof(T).GetField(field, BindingFlags.NonPublic | BindingFlags.Instance).SetValue(obj, value);
    }
}

As seen above, we have two methods, GetField() and SetField().

GetField() takes in the object of type T, along with the string field that you want to access. Just remember to cast the returned object in the calling code.

SetField() takes in the object of type T, along with the string field you want to set, and then the object value itself.

Of course, you can easily add more methods to help access fields, metadata, methods and more through reflection. Highly recommend renaming the file too to be more generic. This should be a good starting point though.

Overall, C# Reflection can be quite useful in helping you set-up Unit Tests, and retrieve values you otherwise wouldn’t have been able to.