WHy should virtual methods be explicitly overridden in C#?
Why should virtual methods be explicitly overridden in 开发者_如何学JAVAC#?
By declaring a method as virtual
, you are stating your intention that the method can be overridden in a derived class.
By declaring your implementing method as override
, your are stating your intention that you are overriding a virtual
method.
By requiring that the override
keyword be used to override a virtual method, the designers of the language encourage clarity, by requiring you to state your intentions.
If you don't add the override
keyword, the method will be hidden (as if it had the new
keyword), not overridden.
For example:
class Base {
public virtual void T() { Console.WriteLine("Base"); }
}
class Derived : Base {
public void T() { Console.WriteLine("Derived"); }
}
Base d = new Derived();
d.T();
This code prints Base
.
If you add override
to the Derived
implementation, the code will print Derived
.
You cannot do this in C++ with a virtual method. (There is no way to hide a C++ virtual method without overriding it)
It is because the C# team members are all skilled C++ programmers. And know how incipient this particular bug is:
class Base {
protected:
virtual void Mumble(int arg) {}
};
class Derived : public Base {
protected:
// Override base class method
void Mumble(long arg) {}
};
It is a lot more common then you might think. The derived class is always declared in another source code file. You don't typically get this wrong right away, it happens when you refactor. No peep from the compiler, the code runs pretty normal, just doesn't do what you expect it to do. You can look at it for an hour or a day and not see the bug.
This can never happen in a C# program. Even managed C++ adopted this syntax, breaking with native C++ syntax intentionally. Always a courageous choice. IntelliSense takes the sting out the extra verbiage.
There's a lot of syntax tweaks in C# that resemble this kind of bug avoidance syntax.
EDIT: and the rest of the C++ community agreed and adopted the override keyword into the new C++11 language specification.
Because it makes code more readable:
class Derived : Base
{
void Foo();
}
In C++, Foo may or may not be a virtual method, we can't tell by looking at the definition. In C# we know a method is virtual (or isn't) because there is either a virtual or override keyword.
Jason's comment below is a better answer.
(edited for clarity)
Not all virtual methods should be overridden, though all abstract methods should (and must) be. As for why the 'override' keyword is explicit, that's because overriding and hiding behave differently. A hiding method is not called through a reference to a base class, whereas an overridden method is. This is why the compiler specifically warns about how you should use the 'new' keyword in the case where you are hiding rather than overriding.
精彩评论