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 baseClass’s 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 doesn’t have that restriction.

| How do you implement Observer Design Pattern in .NET? | How do you pass data between different Tiers in .NET Architecture? | How is Classic ADO different from ADO.NET? | How is Dataadapter useful in ADO.NET? | How is Datareader different from Dataset in ADO.NET? | How is .NET Application Development different from Traditional Development? | How is HashTable different from ArrayList in .NET? | How is Inheritance achieved in C#? | How is new keyword different from override keyword during inheritance in .NET? | How is String class different from StringBuilder class in .NET? | Illustrate ADO.NET Architecture | Illustrate the importance of Server.Transfer and Response.Redirect in .NET? | Mention the different objects available in Dataset of ADO.NET | Mention the usage of Connection Object in ADO.NET | What are the commonly used methods of Dataadapter in ADO.NET? | What are the different Behavioral Design Patterns that can be used in .NET Architecture? | What are the different Creational Design Patterns that can be used in .NET Architecture? | What are the different Structural Design Patterns that can be used in .NET Architecture? | What are the methods provided by Command Objects in ADO.NET? | What is Internal Access Modifier in C#? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.