Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not add a set accessor to an overriden property?

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?

like image 274
Svish Avatar asked Aug 04 '09 12:08

Svish


People also ask

Can you override a property in C#?

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.

Can you override a getter?

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.

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

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.

What is a get or set accessor?

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.


1 Answers

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

like image 198
Arsen Mkrtchyan Avatar answered Sep 28 '22 06:09

Arsen Mkrtchyan