#682 – The Real Reason for the new Keyword

Here’s a scenario that illustrates the main reason for the new keyword, allowing a method to not behave polymorphically.

Suppose you use a third-party library that defines a Dog class and you create a Terrier class in your own code that derives from Dog and defines a Speak method.  (Dog does not have a Speak method).

Now let’s say you get a new version of the Dog library in which they’ve added their own Speak method, which is virtual and which they call from the Dog constructor.

Now, when you construct a Terrier object, the Dog constructor will call Speak.  But by default, it’s Dog.Speak that’s called, rather than Terrier.Speak.  The compiler won’t just automatically make Speak behave polymorphically.

When you re-compile your code, you’ll get a warning indicating that you should make your intent explicit, by either marking Terrier.Speak as new (non-polymorphic) or as override (polymorphic).