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 :)
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).
See more on this question at Stackoverflow