Adding a setter to a virtual property in C#

James Curran picture James Curran · Nov 11, 2010 · Viewed 13.3k times · Source

I have a situation like this:

public abstract class BaseClass 
{
   public abstract string MyProp { get; }
}

Now, for some of the derived classes, the properties value is a synthesized values, so there is no setter:

public class Derived1 : BaseClass
{
    public override string MyProp { get { return "no backing store"; } }
}

This works fine. However, some of the derived class required a more traditional backing store. But, no matter how I write it, as on automatic property, or with an explicit backing store, I get an error:

public class Derived2 : BaseClass
{
    public override string MyProp { get; private set;}
}

public class Derived3 : BaseClass
{
    private string myProp;
    public override string MyProp 
    { 
        get { return myProp;} 
        private set { myProp = value;}
    }
}

Derived2.MyProp.set': cannot override because 'BaseClass.MyProp' does not have an overridable set accessor

How do I get this to work??

Answer

Bradley Smith picture Bradley Smith · Nov 11, 2010

The best thing you can do is implement the property as virtual instead of abstract. Make the get and set blocks for each throw NotSupportedException in the base class and override the behaviour accordingly in derived classes:

public virtual string MyProp {
    get {
        throw new NotSupportedException();
    }
    set {
        throw new NotSupportedException();
    }
}