Is it possible to add an accessor to a property in .NET by overriding it?

Is it possible to do something like this?

class A { public virtual string prop { get { return "A"; } } } class B: A { private string X; public override string prop { get { return X; } set { X = value; } } } 

That is, the base class provides a virtual property only with GET accessories, but the child class overrides GET and also provides SET.

The current example does not compile, but maybe I am missing something.

Added: To clarify, no, I do not want to redefine the new one. I want to add a new accessor. I know that this was not in the base class, so it cannot be overestimated. Ok, let me try to explain how it would look without syntactic sugar:

 class A { public virtual string get_prop() { return "A"; } } class B: A { private string X; public override string get_prop() { return X; } public virtual string set_prop() { X = value; } } 
+4
source share
4 answers

No, It is Immpossible. Unfortunately, you cannot even redefine and change the access level (for example, from secure to public), as described in MSDN . I would advise you to consider restructuring the code / class and look for an alternative way to accomplish this task, such as declaring an access set with a protected modifier using the SetProperty method in a derived class.

+1
source

No, there is no way to do this. Think about how the syntactic sugar of your virtual property is handled, i.e. It is converted to:

 public virtual string get_prop(); 

There is no set_Prop method to override, and you cannot override a method that does not exist.

+1
source

You can hide the base class implementation using the keyword "new" in the derived class. The following should compile successfully:

 class A { public virtual string prop { get { return "A"; } } } class B : A { private string X; public new string prop { get { return X; } set { X = value; } } } 
0
source

Presentation of a new field looks like dirty. And in any case, you need to be careful not to violate polymorphism and inheritance (what if the base class speaks with a private field?).

As for adding a new accessory when redefining; the simple answer is no, you cannot. When you redefine, you can only work on existing accessors, since this is what is defined in the virtual table for the member (the redefined element still "belongs" to the base / declaring class, and not to the override class).

One option (not perfect) is to re-declare the property, but you still need a way to talk to the base class. Therefore, if the accessor in the base class was protected :

 class A { public string prop { get; protected set; } } class B : A { public new string prop { get { return base.prop; } set { base.prop = value; } } } 
0
source

All Articles