williamsandonz
williamsandonz

Reputation: 16420

C# how to override like this?

the code below is saying a() cannot override a() as wee.a() is not marked virtual, abstract or override. Is there a a way around this? I need to have code inside the super method, but still want to override it!

public abstract class wee
{
  public void a()
  {

  }
}
public class dee : wee
{
  public override void a()
  {
  }
  public void b()
  {
  }
}

Upvotes: 1

Views: 172

Answers (3)

Jay
Jay

Reputation: 6294

It will not override the method, there is no way to do this without marking the base as such. If you don't want to modify the base as others have suggested, instead you can hide the base method like this:

public class dee : wee
{
    public new void a()
    {
    }
    public void b()
    {
    }
}

Upvotes: 2

Nate
Nate

Reputation: 30636

Mark wee.a() as virtual -- it allows you to provide a base implementation but gives the option to override that behavior in subclasses if needed.

// wee
public virtual void a() { // do stuff for base implementation }

// dee
public override void a() { // override behavior implemenation }

Upvotes: 1

jrummell
jrummell

Reputation: 43067

You need to mark wee.a virtual or abstract.

Virtual:

public abstract class wee
{
  public virtual void a()
  {

  }
}

public class dee : wee
{
  public override void a()
  {
  }
  public void b()
  {
  }
}

Abstract:

public abstract class wee
{
  public abstract void a();
}

public class dee : wee
{
  public override void a()
  {
  }
  public void b()
  {
  }
}

Upvotes: 9

Related Questions