How
is new keyword different from override keyword during inheritance in .NET?
The keyword
new is used to create a new method in the derived class with the same
name as that of base class method, but both of them are two different.
The keyword override is used to override a base class method inside the
derived class.
Here is an
example:
class baseClass
{
public virtual void displayMsg() {
Console.WriteLine(Calling displayMsg of baseClass which can be overridden);
}
public void displayMsg2() {
Console.WriteLine(Calling baseClasss displayMsg2 that cannot
be overridden);
}
}
class derivedClass:baseClass {
public override void displayMsg() {
Console.WriteLine(Overriding displayMsg in derivedClass);
}
public new void displayMsg2() {
Console.WriteLine(This is a new method belonging to derivedClass
alone);
}
}
In this example, you override the virtual method displayMsg of baseClass
in derivedClass and you create a new method displayMsg2 in derivedClass
that is not related to displayMsg2 of baseClass. Remember that overriding
method should have same signature as that of base class method but methods
defined using new keyword doesnt have that restriction.