Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override the setter method of a property in C#?

I have a class with a subclass. The superclass has a Position property. The subclass must perform an additional operation when the Position property is changed, so I am attempting to override the setter method and call the superclass' setter.

I think I've got the superclass setter calling part down, but I can't figure out how the overriding syntax works here.

Here is my best attempt: code

The getter is there just for proof of concept -- suppose I wanted to override that too?

The getter and setter give me errors of this form:

cannot override inherited member 'superClassName.Position.[gs]et' because it is not marked virtual, abstract, or override

Here's a screencap of the errors too for good measure: errors

I also tried using the override keyword in front of the set. Removing the superfluous getter has no effect.

What is the correct syntax?

like image 896
Anko Avatar asked Jun 17 '11 11:06

Anko


People also ask

How do you override a base class property?

you can override properties just like methods. That is, if the base method is virtual or abstract. You should use "new" instead of "override". "override" is used for "virtual" properties.

Can properties be overridden?

You cannot "override" fields, because only methods can have overrides (and they are not allowed to be static or private for that). This trick lets A 's subclasses "push" a new value into the context of their superclass, getting the effect similar to "overriding" without an actual override.

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.


1 Answers

The override is fine. However, as the error message states, you need to mark the property in the base class as virtual to be able to override it:

public virtual Vector2 Position 

Unlike Java, class members are not virtual by default in C#. If you can't change the base class, you're out of luck.

like image 162
dtb Avatar answered Sep 23 '22 23:09

dtb