Setting a Private Field on an instance of an object using Reflection

For sure this is not a best practice, although I thought of using this in a hacky way to inject a value into a private field of a class, I ended up not using this code anywhere. It is amazing the freedom you get when you use reflection, you can do just about anything!

Let’s start by checking the Person class, which contains a private string for name:

public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        private set { name = value; }
    }

    public Person(string name)
    {
        this.name = name;
    }
}

Since the set for the Name property as a private access modifier we will not be able to set a Person’s name the normal way. As we want to access the private field name from outside of the class, let us create an helper method that does just that, and generalize it so that we can use it anywhere:

public static void SetField<T>(T instance, string fieldName, object obj)
{
    var f = typeof(T)
        .GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
    if (obj.GetType() != f.FieldType)
        throw new InvalidOperationException("Types do not match!");
    f.SetValue(instance, obj);
}

Supposing we have a the SetField method in scope, we can call it passing an instance of an object, the name of the field (private or not) to be set and the object to set it to. Using the previous Person class we can easily call:

SetField(person, "name", "Jason");

Et voilá! The name of person gets set to Jason, even though the access modifier on the field is private.

If you want to download a full working sample for this example please follow this link.

Leave a Reply

Your email address will not be published. Required fields are marked *