override a setter on a subclass in csharp

To override a setter in a subclass in C#, you must first define a property with the same name as the property in the superclass. Then, you can use the override keyword to define a new implementation for the setter.

main.cs
public class Superclass {
    private string _myProperty;
    public virtual string MyProperty {
        get { return _myProperty; }
        set { _myProperty = value; }
    }
}

public class Subclass : Superclass {
    private string _myPropertyOverride;
    public override string MyProperty {
        get { return base.MyProperty; }
        set { _myPropertyOverride = value; }
    }
}
389 chars
16 lines

In this example, the superclass has a property called MyProperty with a getter and setter. The subclass defines a new implementation of the setter using the override keyword. Within that setter, it calls the base implementation of the getter using base.MyProperty to preserve the original behavior of the property. However, it sets a new value to a separate field _myPropertyOverride.

By doing this, the subclass is able to extend the behavior of the property without completely replacing it.

gistlibby LogSnag