tags:

views:

62

answers:

2

Is there a way to declare a setter for a clr-property that is defined in an abstract base class with only a getter (and vice versa)?

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

class ConcreteClass : BaseClass{
    public override string Test {
        get { return string.Empty; }
        set { /* Some code*/} // This would be really pratically
    }
}

The same quesion may be asked for properties marked as virtual.

+5  A: 

That is fortunately not possible. You cannot change an existing definition/contract.

There are ways around it, like the new keyword. Or using an interface.

leppie
new is not a way around it new is something different that looks like the same.BaseClass foo = getFoo();string myFoo = foo.Test;andConcreteClass foo = (ConcreteClass)getFoo();string myFoo = foo.Test; might yield different results for the _same_ object
Rune FS
Which definition/contract would be broken? It’s only an additional method in the derived class. But yes, it seems not possible. Thanks a lot for the answer.
HCL
+2  A: 

There is a sort of a workaround possible.

Declare a protected setter in the base class, then implement it in the concrete classes.

Like this:

abstract class Base
{
    public abstract string Test { get; protected set; }

}

class Concrete : Base
{
    string s;
    public override string Test
    {
        get { return s; }
        protected set { s = value; }
    }
}

... but pretty, it ain't :-)

corvuscorax
Thanks for the answer, this declaration is possible, however not what I'm looking for.
HCL