I’ve read about new keyword in method signature and have seen the example below on this post, but I still don’t get why to write new keyword in method signature. If we’ll omit it, it still will do the same things. It will compile. There is gonna be a warning, but it will compile.
So, writing new in method signature is just for readability?
public class A
{
public virtual void One() { /* ... */ }
public void Two() { /* ... */ }
}
public class B : A
{
public override void One() { /* ... */ }
public new void Two() { /* ... */ }
}
B b = new B();
A a = b as A;
a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B
Implicit in this question: why isn’t the
newkeyword required when hiding a base class member? The reason is the brittle base class problem. Suppose you have a library:and you’ve derived a class in your own code base:
Now, the library authors release a new version, adding another method to
Base:If the new keyword were required for method hiding, your code now fails to compile! Making the new keyword optional means that all you now have is a new warning to worry about.
EDIT
As Eric Lippert points out in his comment, “new warning to worry about” drastically understates the purpose of the warning, which is to “wave a big red flag.” I must have been in a hurry when I wrote that; it’s annoying when people reflexively view warnings as annoyances to be tolerated rather than treating them as useful information.
EDIT 2
I finally found my source for this answer, which, of course, is one of Eric’s posts: https://stackoverflow.com/a/8231523/385844