2

Given that I have the following code:

interface IBase {
    void DoStuff(double x, double y);
}

class Base : IBase {
    public void DoStuff(double x, double y) { Console.WriteLine(x + y); }
}

Is it a good practice to override/hide the behavior of the base class without actually using the override keyword? Are there any hidden pitfalls in the code below?

class Derived : Base {
    public void DoStuff(double x, double y) { Console.WriteLine(x * y); }
}

Is it any better to use the new keyword here? Like so:

class Derived : Base {
    public new void DoStuff(double x, double y) { Console.WriteLine(x * y); }
}
mbadawi23
  • 1,029
  • 2
  • 21
  • 43
  • 1
    `public void DoStuff` and `public new void DoStuff` have 0 differences in behavior except the first one throws a compiler warning and the 2nd does not. – Scott Chamberlain May 03 '16 at 00:21

1 Answers1

5

Is it a good practice to override/hide the behavior of the base class without actually using the override keyword?

You can't "override" the base method because it's not virtual. All you can do is hide it. It is very rarely a "good practice" but there's nothing that prevents it, so whether it's "good" or not is highly contextual.

Is it any better to use the new keyword here?

Using new doesn't change the functionality in the slightest. The keyword is there so that you can explicitly tell the compiler "I know that I'm hiding a base member". The behavior will be the same whether you use new or not.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Would it be best if I changed the code to define the method as virtual in base? the problem here should there be a `class BaseB: IBase`, there is no way to enforce declaring the method as virtual. – mbadawi23 May 03 '16 at 00:34
  • You can make it `abstract` to force inheritors to provide their own implementation, but there's no way to "force" a class to make a method `virtual` – D Stanley May 03 '16 at 00:42
  • Great, that is exactly what I was looking for. Would you include this in your answer as well. Thanks. – mbadawi23 May 03 '16 at 00:44