I have this Base class:
abstract class Base { public int x { get { throw new NotImplementedException(); } } }
And the following descendant:
class Derived : Base { public int x { get { //Actual Implementaion } } }
When I compile I get this warning saying Derived class's definition of x
is gonna hide Base's version of it. Is is possible to override properties in c# like methods?
An overriding property declaration must specify exactly the same access modifier, type, and name as the inherited property. Beginning with C# 9.0, read-only overriding properties support covariant return types. The overridden property must be virtual , abstract , or override .
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.
In C#, a method in a derived class can have the same name as a method in the base class. You can specify how the methods interact by using the new and override keywords. The override modifier extends the base class virtual method, and the new modifier hides an accessible base class method.
You need to use virtual
keyword
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 override
keyword when in the child:
abstract class Derived : Base { // use override keyword public override int x { get { ... } } }
If you're NOT going to override, you can use new
keyword on the method to hide the parent's definition.
abstract class Derived : Base { // use new keyword public new int x { get { ... } } }
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