In a base class I have this property:
public virtual string Text
{
get { return text; }
}
I want to override that and return a different text, but I would also like to be able to set the text, so I did this:
public override string Text
{
get { return differentText; }
set { differentText = value; }
}
This however does not work. I get a red squiggly under set
saying that I can not override because it does not have a set accessor. Why is this aproblem? What should I do?
In C#, class methods, indexers, properties and events can all be overridden. Non-virtual or static methods cannot be overridden. The overridden base method must be virtual, abstract, or override. In addition to the modifiers that are used for method overriding, C# allows the hiding of an inherited property or method.
To override the getter method for a property, modify the class that contains the property and add a method as follows: It must have the name PropertyNameGet, where PropertyName is the name of the corresponding property. It takes no arguments. Its return type must be the same as the type of the property.
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.
In properties, a get accessor is used to return a property value and a set accessor is used to assign a new value. The value keyword in set accessor is used to define a value that is going to be assigned by the set accessor. In c#, the properties are categorized as read-write, read-only, or write-only.
public virtual string Text
{
get { return text; }
protected set {}
}
change base class property like this, you are trying to override set method that doesn't exist
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