add a setter to a subclass in csharp

To add a setter to a subclass property in C#, you can simply declare the property with a public set method in the subclass definition. Here's an example:

main.cs
public class MySuperclass
{
    public int MyProperty { get; set; }
}

public class MySubclass : MySuperclass
{
    public void SetMyProperty(int newValue)
    {
        base.MyProperty = newValue;
    }
}
206 chars
13 lines

In this example, MySubclass inherits the MyProperty property from MySuperclass, but it adds a new method SetMyProperty to set the value of MyProperty. This method simply calls the base class's set method, passing the new value.

Encapsulation is maintained because the MyProperty property remains hidden from external access and can only be modified through SetMyProperty method.

gistlibby LogSnag