In the previous article, I explained the use of the Virtual & Override keywords. They are used for Method overriding concepts in polymorphism.
In this article, I am going to explain about the "New" modifier keyword. Let us see the below example first.
Programming Example 1 - without new modifier
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace VirtualOverrideNew {
- class Circle {
- public void Area(double r) {
- Console.WriteLine(String.Format("Area of Circle : {0}", Math.PI * r * r));
- }
- }
- class Sphere: Circle {
- public void Area(double r) {
- Console.WriteLine(String.Format("Area of Circle : {0}", 4 * Math.PI * r * r));
- }
- }
- class Program {
- static void Main(string[] args) {
- Circle C = new Sphere();
- C.Area(4);
- }
- }
- }
OutPut
Area of Circle: 50.2654824574367
I have implemented the inheritance concept in the above example. Here, the same method is defined in both base class & derived class. The code is also successfully compiled but shows a warning message during the compilation time.
It tells us to use the new keyword to hide the inherited member. So, by using the new modifier in the derived class method, it hides the implementation of the base class method. This is called Method Hiding. It allows you to provide a new implementation for a derived class.
Programming Example 2 - using new modifier
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace VirtualOverrideNew {
- class Circle {
- public void Area(double r) {
- Console.WriteLine(String.Format("Area of Circle : {0}", Math.PI * r * r));
- }
- }
- class Sphere: Circle {
- public new void Area(double r) {
- Console.WriteLine(String.Format("Area of Circle : {0}", 4 * Math.PI * r * r));
- }
- }
- class Program {
- static void Main(string[] args) {
- Circle C = new Sphere();
- C.Area(4);
- }
- }
- }
OutPut
Area of Circle: 50.2654824574367
Conclusion
After the compilation of the above code, the warning is removed.This article explained the concept of Method Hiding using New modifier. I hope you enjoyed it.
If you have any queries, please comment.
Thanks!