Home »
.Net »
C# Programs
C# - Implement Method Hiding
Here, we are going to learn how to implement method hiding using C# program?
Submitted by Nidhi, on September 10, 2020 [Last updated : March 22, 2023]
Here, we will create two classes Sample and Demo. Then inherit the Sample class into the Demo class. And, we defined method Method2() in both of the classes. In the derived class Demo, we gave a completely new definition and hide the inherited definition using the 'new' keyword.
C# program to implement method hiding
The source code to demonstrate the concept of method Hiding is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# - Implement Method Hiding.
using System;
public class Sample
{
public virtual void Method1()
{
Console.WriteLine("Sample: Method1() called");
}
public void Method2()
{
Console.WriteLine("Sample: Method2() called");
}
}
public class Demo : Sample
{
public override void Method1()
{
Console.WriteLine("Demo: Method1() called");
}
public new void Method2()
{
Console.WriteLine("Demo: Method2() called");
}
}
public class Program
{
public static void Main(string[] args)
{
Demo Ob = new Demo();
Ob.Method1();
Ob.Method2();
}
}
Output
Demo: Method1() called
Demo: Method2() called
Press any key to continue . . .
Explanation
In the above program, we created three classes Sample, Demo, and Program. Here we inherited the Sample class into the Demo class and override the Method1() in the Demo class. Here we also defined method Method2() in both classes. In the derived class Demo, we gave a completely new definition and hide the inherited definition using the new keyword.
The Program class contains the Main() method, In the Main() method we created the object Ob of Demo class and then called Method1() and Method2().
C# Basic Programs »