override a private property on a subclass in csharp

In C#, we can override the properties of a base class in a subclass using the override keyword. However, if the property in the base class is declared as private, it is not accessible in the subclass. In that case, we can use a protected property or method to access and modify the private property in the base class.

Here's an example:

main.cs
public class MyBaseClass
{
    private int myPrivateProperty;

    protected int MyProtectedProperty
    {
        get { return myPrivateProperty; }
        set { myPrivateProperty = value; }
    }

    public int MyPublicProperty { get; set; }
}

public class MySubClass : MyBaseClass
{
    public MySubClass()
    {
        MyProtectedProperty = 10; // accessing and modifying the private property through the protected property
        MyPublicProperty = 20; // accessible directly
    }

    public new int MyPublicProperty { get; set; } // hiding the base class property with a new property
}
598 chars
24 lines

In the example above, we're accessing and modifying the private myPrivateProperty through the protected MyProtectedProperty in the MySubClass. We're also hiding the base class public property MyPublicProperty with a new public property in the MySubClass.

gistlibby LogSnag