3

This is a C# project.

I have several classes inherited from a base class. Most of the child classes have the same behavior while some of them behave differently.

I'm using the new keyword.

public class Parent
{
    public DataTable FetchScore()
    {
        // blahblah
    }
}

public class ChildNormal : Parent
{
}

public class ChildOdd : Parent
{
    public new DataTable FetchScore()
    {
        DataTable dt = base.FetchScore();
        // blahblah
    }
}

But the build says using new is not a good practice.

I cannot use virtual and override either, because I want a default. I don't want to copy the same override implementation many times.

How do I do this in C#?

Rob
  • 172
  • 6
hbrls
  • 2,110
  • 5
  • 32
  • 53
  • 1
    You can use virtual and override, just place the virtual base methods in the base class. – Lasse V. Karlsen Sep 02 '14 at 10:12
  • Also see [here](http://stackoverflow.com/questions/11046387/exact-difference-between-overriding-and-hiding) for *why* using `new` is (probably) not what you want to do. – Rawling Sep 02 '14 at 10:18

1 Answers1

1

You need to declare the base virtual (which means it can be overridden if necessary) and override it where you need different behavior from the original. The non-overridden derived class will behave just like the base class.

public class Parent()
{
    public virtual DataTable FetchScore()
    {
        // blahblah
    }
}

public class ChildNormal() : Parent
{
}

public class ChildOdd() : Parent
{
    public override DataTable FetchScore()
    {
        DataTable dt = base.FetchScore();
        // blahblah
    }
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142