Search code examples
c#inheritancepropertiesoverridingabstract-class

Override set part of a property from base abstract class in the subclass C#


I have an abstract class called A that is the base class for another class called B. I want to override the DrawingType property in B. Here is my code:

public abstract class A
{
    protected DrawingType m_type;

    public DrawingType Type
    {
        get { return m_type; }
        set { m_type = value}
    }
}

public B : A
{
    // I want to override the 'set' of DrawingType property here.
}

How can I override the DrawingType property in B?


Solution

  • Your classes should look like the following:

    abstract class A
    {
        protected DrawingType m_type;
    
        protected virtual DrawingType Type
        {
            get { return m_type; }
            set { m_type = value; }
        }
    }
    
    class B : A
    {
        protected override DrawingType Type
        {
            get
            {
                return m_type;
            }
            set
            {
                m_type = //custom logic goes here
            }
        }
    }
    

    If the base class doesn't have an implementation you can use

    abstract class A
    {
        protected DrawingType m_type;
    
        protected abstract DrawingType Type { get; set; }
    }