Can I override a property in C #? How?

I have this base class:

abstract class Base { public int x { get { throw new NotImplementedException(); } } } 

And the next descendant:

 class Derived : Base { public int x { get { //Actual Implementaion } } } 

When I compile, I get this warning saying that the Derived definition of class x will hide the base version. Is it possible to override properties in C # -like methods?

+55
override inheritance polymorphism c # properties
Dec 09 '11 at 15:36
source share
5 answers

You need to use the virtual

 abstract class Base { // use virtual keyword public virtual int x { get { throw new NotImplementedException(); } } } 

or define an abstract property:

 abstract class Base { // use abstract keyword public abstract int x { get; } } 

and use the override keyword when in it:

 abstract class Derived : Base { // use override keyword public override int x { get { ... } } } 

If you are NOT going to override, you can use the new keyword in a method to hide the parent definition.

 abstract class Derived : Base { // use override keyword public new int x { get { ... } } } 
+74
Dec 09 '11 at 15:37
source share

Make the underlying property abstract and override or use a new keyword in a derived class.

 abstract class Base { public abstract int x { get; } } class Derived : Base { public override int x { get { //Actual Implementaion } } } 

or

 abstract class Base { public int x { get; } } class Derived : Base { public new int x { get { //Actual Implementaion } } } 
+11
Dec 09 '11 at 15:38
source share

Change the property signature as shown below:

Base class

 public virtual int x { get { /* throw here*/ } } 

Derived class

 public override int x { get { /*overriden logic*/ } } 

If you do not need an implementation in the base class, just use the abstract property.

Base:

 public abstract int x { get; } 

Derivative:

 public override int x { ... } 

I suggest you use the abstract property, rather than trhowing the NotImplemented exception in the getter, the abstact modifier will force all derived classes to implement this property so that you eventually find a solution that is safe for compilation.

+3
Dec 09 '11 at 15:39
source share
 abstract class Base { // use abstract keyword public virtual int x { get { throw new NotImplementedException(); } } } 
+3
Dec 09 '11 at 15:40
source share
 abstract class Base { public virtual int x { get { throw new NotImplementedException(); } } } 

or

 abstract class Base { // use abstract keyword public abstract int x { get; } } 

In both cases, you need to write in a derived class

 public override int x { get { your code here... } } 

the difference between the two is that with abstract you force the derived class to implement something, and with virtaul you can provide default behavior that the derivative can use as is or change.

+2
Dec 09 '11 at 15:40
source share



All Articles