override
new
The C# team posts answers to common questions and describes new language features
This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance:
public class Base { public virtual void SomeMethod() { } } public class Derived : Base { public override void SomeMethod() { } } ... Base b = new Derived(); b.SomeMethod();
will end up calling Derived.SomeMethod if that overrides Base.SomeMethod. Now, if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code like this:
Derived.SomeMethod
Base.SomeMethod
public class Base { public virtual void SomeOtherMethod() { } } public class Derived : Base { public new void SomeOtherMethod() { } } ... Base b = new Derived(); Derived d = new Derived(); b.SomeOtherMethod(); d.SomeOtherMethod();
Will first call Base.SomeOtherMethod (line 3), then Derived.SomeOtherMethod (line 4). They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.
Base.SomeOtherMethod
Derived.SomeOtherMethod
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
overrides
That provides the basics of overriding and the difference between new and override, but you should really see a book or tutorial for a more in-depth look at polymorphism.
[Author: Jon Skeet]
good ex : blog.flair-systems.com/.../c-fastfood-difference-between-override.html
great article.. thanks
Nice.pls explain fragile base class problem .............
yeah, a good answer for me to understand what "hide" and "override" means. Thanks :-)
Good article, helps me a lot.
I think both "override" and "new" are something of security mechanism which is used to remind programmer possible spelling mistake in codes.