I have an abstract class that defines a get
, but not set
, because as far as that abstract class is concerned, it needs only a get
.
public abstract BaseClass { public abstract double MyPop {get;} }
However, in some of the derive class, I need a set
property, so I am looking at this implementation
public class DClass: BaseClass { public override double MyPop {get;set;} }
The problem is, I got a compilation error, saying that
*.set: cannot override because *. does not have an overridable set accessor.
Even though I think that the above syntax is perfectly legitimate.
Any idea on this? Workaround, or why this is so?
Edit: The only approach I can think of is to put both get
and set
as in the abstract class, and let the subclass throws a NotImplementedException
if set
is called and it's not necessary. That's something I don't like, along with a special setter method .
In C# 8.0 and earlier, the return types of an override method and the overridden base method must be the same. You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method.
A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.
In C#, a method in a derived class can have the same name as a method in the base class. You can specify how the methods interact by using the new and override keywords. The override modifier extends the base class virtual method, and the new modifier hides an accessible base class method.
The error "'X' is defined as a property in class 'Y', but is overridden here in 'Z' as an accessor" occurs when a property overrides an accessor or vice versa in a derived class. To solve the error, use properties or accessors in both classes for the members you need to override.
One possible answer would be to override the getter, and then to implement a separate setter method. If you don't want the property setter to be defined in the base, you don't have many other options.
public override double MyPop { get { return _myPop; } } public void SetMyPop(double value) { _myPop = value; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With