override setter in class in csharp

To override a setter in a class in C#, you first have to create the property in the base class with the "virtual" keyword. This will allow any derived classes to override it. Then, in the derived class, you can use the "override" keyword to provide your own implementation of the setter.

Here's an example:

main.cs
public class BaseClass
{
    private int _myProperty;

    public virtual int MyProperty
    {
        get { return _myProperty; }
        set { _myProperty = value; }
    }
}

public class DerivedClass : BaseClass
{
    private string _myOtherProperty;

    public override int MyProperty
    {
        get { return base.MyProperty; }
        set
        {
            _myOtherProperty = $"Property value: {value}";
            base.MyProperty = value;
        }
    }
}
472 chars
26 lines

In this example, the base class has a property called "MyProperty" that is marked as virtual, so it can be overridden. The derived class provides its own implementation of the setter, which sets a private field called "_myOtherProperty" to a concatenated string and then calls the base class's setter to set the actual value.

gistlibby LogSnag