Method Hiding/ Method Shadowing In C#

 

Method Hiding In c#

C# also provides a concept to hide the methods of the base class from derived class, this concept is known as Method Hiding.  It is also known as Method Shadowing.


* you can hide the implementation of the methods of a base class from the derived class using the new keyword. 


// Base Class 

public class My_Family {   

    public void member() 

    { 

        Console.WriteLine("Total number of family members: 3"); 

    } 

  

// Derived Class 

public class My_Member : My_Family {   

    // Reimplement the method of the base class 

    // Using new keyword 

    // It hides the method of the base class 

    public new void member()  

    { 

        Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya, "+ 

                               "Age: 39 \nName: Rohan, Age: 20 "); 

    } 

  

// Driver Class 

class Program{   

    // Main method 

    static public void Main() 

    { 

        // Creating the object of the derived class 

        My_Member obj = new My_Member();   

        // Access the method of derived class 

        obj.member(); 

    } 

Output:


Name: Rakesh, Age: 40 

Name: Somya, Age: 39 

Name: Rohan, Age: 20 



How to call a hidden method?

By using the base keyword you can call the hidden method of the base class in your derived class shown in the below example:

// Base Class 

public class My_Family {   

    public void member() 

    { 

        Console.WriteLine("Total number of family members: 3"); 

    } 

  

// Derived Class 

public class My_Member : My_Family {  

    public new void member()  

    { 

  // Calling the hidden method of the
        // base class in a derived class
        // Using base keyword
        base.member();

        Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya,"+

                              " Age: 39 \nName: Rohan, Age: 20"); 

    } 

  

// Driver Class 

class Program{   

    // Main method 

    static public void Main() 

    { 

        // Creating the object of the derived class 

        My_Member obj = new My_Member();   

        // Access the method of derived class 

        obj.member(); 

    }