Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 779
atoMerz Avatar asked Dec 09 '11 15:12

atoMerz


People also ask

How do you override a property?

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 .

How do you override a base class property?

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.

Can you override a class C#?

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.


1 Answers

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 { ... } } } 
like image 97
Jeffrey Zhao Avatar answered Oct 09 '22 20:10

Jeffrey Zhao