Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override get, but not set

Tags:

c#

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 .

like image 790
Graviton Avatar asked Jan 08 '10 09:01

Graviton


People also ask

Can we override a property in C#?

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.

What is the use of get and set properties in C#?

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.

What is difference between new and override in C#?

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.

Is defined as a property in class but is overridden here in?

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.


1 Answers

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; } 
like image 196
David M Avatar answered Nov 09 '22 18:11

David M