Can I override a property in c#? How?

浪尽此生 提交于 2019-11-27 07:43:49
Jeffrey Zhao

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 override keyword
  public new int x { get { ... } }
}

Make the base property abstract and override or use the new keyword in the 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 }
  }
}

Change 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 any implementation in Base class just use abstract property.

Base:

public abstract int x { get; }

Derived:

public override int x { ... }

I would suggest you using abstract property rather than trhowing NotImplemented exception in getter, abstact modifier will force all derived classes to implement this property so you'll end up with compile-time safe solution.

abstract class Base 
{ 
  // use abstract keyword 
  public virtual int x 
  { 
    get { throw new NotImplementedException(); } 
  } 
} 
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 case you have to write in the derived class

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!