0

I get the difference between virtual/override and new modifiers. But what about times when I don't specify any modifiers.

For example I have Animal and Cat classes (Cat inherits Animal).

Animal class has method:

public void Say()
{
    // do something
}

And Cat class has method:

public void Say()
{
    // do something else
}

When I'm working with this methods they work as if I used new keyword.

Visual Studio shows me a warning (Use new keyword if hiding was intended).

Why does compiler won't break when I don't specify keyword. It just magically works with a little warning. Can I use some strict mode or may be edit settings in IDE.

Or may be it's a feature that I don't get :)

2tunnels
  • 85
  • 3
  • 6
  • possible duplicate of [C# keyword usage virtual+override vs. new](http://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new) – Steve Mitcham Jan 28 '15 at 13:16
  • It is just a warning, reminding you that you are *probably* doing something wrong. You probably are and meant Say() to be a virtual method. The *new* keyword does only one thing, it suppresses the warning. – Hans Passant Jan 28 '15 at 13:16
  • @HansPassant, yes I know I'm doing it wrong. I'm just curious why can I skip such important keyword. – 2tunnels Jan 28 '15 at 13:19
  • You are allowed to do it wrong, you don't always have the luxury to modify a base class. Sometimes it is useful, it works well in Winforms for example. It relies heavily on Reflection so isn't so easily broken by a muddled inheritance chain. – Hans Passant Jan 28 '15 at 13:23

2 Answers2

8

Why does compiler won't break when I don't specify keyword.

To avoid the "brittle base class" problem - where Cat originally has the Say() method, and then the author of Animal wants to add a Say() method too. With the current approach, that is not a breaking change - it will create a warning for the author of Cat, but that's all. The behaviour of all code will stay the same. The author of Cat can then decide what to do about their Say method - add the new modifier, or override Animal.Say() if that's virtual, or potentially rename the method to avoid confusion (if they control all clients as well).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
-4

For Animal class public virtual void Say(). For Cat public override void Say(). Then always define object of type Animal:

Animal my_cat = new Cat();
my_cat.Say();
i486
  • 6,491
  • 4
  • 24
  • 41