Search code examples
c#.netoopprivateencapsulation

Can you modify a private field of a super class?


I'm working with a closed-source base class. Can I somehow change a private field in the base class from my inheriting class?

Assuming the following class structure:

public class Parent
{
    private bool age;
}

public class Baby : Parent  
{
    public bool newAge{
        get {
           return age;
        }
    }
}

This currently gives you a compile-time error:

 'Parent.age' is inaccessible due to its protection level.

How do you access the field "age" from the Baby class? Can you use reflection or something similar?


Solution

  • You could, using reflection. It looks like this:

    public class Baby : Parent
    {
        private readonly FieldInfo _ageField = typeof(Parent).GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
        public int newAge
        {
            get
            {
                return (int)_ageField.GetValue(this);
            }
            set
            {
                _ageField.SetValue(this, value);
            }
        }
    } 
    

    If it's provided by a 3rd party, there is nothing stopping them from changing it, renaming it, it removing it all together. That's one of the points of private. Keep in mind that it might be private for a reason. Tinkering where you aren't suppose to can lead to unexpected results.