Sina Iravanian

I blog about software development

Assigning Values to Private Fields Using Reflection

| Comments

Suppose that you have a class with various non-public fields, e.g., the class named ClassToTest below servers as a good example.

1
2
3
4
5
6
7
8
9
public class ClassToTest
{
    public int SomeNumber { get; set; }

    private int m_somePrivateProperty { get; set; }
    private int m_somePrivateVar;

    private static int s_someStaticNumber;
}

And suppose that we desire to assign some value to the private variable m_somePrivateVar, and the private property m_somePrivateProperty. The approach is to iterate through the fields of the ClassToTest type to find the desired field. If it is a variable we should type-cast it to FieldInfo, and if it is a property we should type-cast it to PropertyInfo. Then we should call the SetValue method appropriately. This is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ClassToTest c = new ClassToTest();

Type t = typeof(ClassToTest);
foreach (var member in t.GetMembers(BindingFlags.Instance |
                                    BindingFlags.NonPublic |
                                    BindingFlags.Public))
{
    if (member.Name == "m_somePrivateVar")
    {
        // changing the variable
        FieldInfo fi = (FieldInfo)member;
        fi.SetValue(c, 18);
    }
    else if (member.Name == "m_somePrivateProperty")
    {
        // changing the property
        PropertyInfo pi = (PropertyInfo)member;
        pi.SetValue(c, 13, null);
    }
}

Here we have successfully assigned values to selected private fields of our class.

Comments