Method Hiding In C#

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
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace VirtualOverrideNew {  
  7.     class Circle {  
  8.         public void Area(double r) {  
  9.             Console.WriteLine(String.Format("Area of Circle : {0}", Math.PI * r * r));  
  10.         }  
  11.     }  
  12.     class Sphere: Circle {  
  13.         public void Area(double r) {  
  14.             Console.WriteLine(String.Format("Area of Circle : {0}", 4 * Math.PI * r * r));  
  15.         }  
  16.     }  
  17.     class Program {  
  18.         static void Main(string[] args) {  
  19.             Circle C = new Sphere();  
  20.             C.Area(4);  
  21.         }  
  22.     }  
  23. }  
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
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace VirtualOverrideNew {  
  7.     class Circle {  
  8.         public void Area(double r) {  
  9.             Console.WriteLine(String.Format("Area of Circle : {0}", Math.PI * r * r));  
  10.         }  
  11.     }  
  12.     class Sphere: Circle {  
  13.         public new void Area(double r) {  
  14.             Console.WriteLine(String.Format("Area of Circle : {0}", 4 * Math.PI * r * r));  
  15.         }  
  16.     }  
  17.     class Program {  
  18.         static void Main(string[] args) {  
  19.             Circle C = new Sphere();  
  20.             C.Area(4);  
  21.         }  
  22.     }  
  23. }  
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!