Can I override a property in c#? How?

atoMerz picture atoMerz · Dec 9, 2011 · Viewed 80.8k times · Source

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?

Answer

Jeffrey Zhao picture Jeffrey Zhao · Dec 9, 2011

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 { ... } }
}