Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a setter to a virtual property in C#

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??

like image 933
James Curran Avatar asked Nov 11 '10 05:11

James Curran


2 Answers

Basically, you cannot. By adding a setter you are changing the definition of the property, so it does not really "override" the base property. It's the same as if you tried to override a method and add another parameter to it - they would be treated as different methods (overloaded). Since properties cannot be overloaded this won't work.

You'll just have to add another method to set the value (perhaps with protected accessibility).

like image 135
EMP Avatar answered Oct 22 '22 04:10

EMP


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();
    }
}
like image 43
Bradley Smith Avatar answered Oct 22 '22 05:10

Bradley Smith