C# Program to Demonstrate Method Hiding

This is a C# Program illustrate method hiding.

Problem Description

This C# Program Illustrates Method Hiding.

Problem Solution

Here a method func() in the base class and in the derived class give a completely new definition to the same method by preceding it with ‘new’ keyword

Program/Source Code

Here is source code of the C# Program Illustrate Method Hiding. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program Illustrate Method Hiding
 */
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    public class Demo
    {
        public virtual double Area(double r)
        {
            return r * r;
        }
        public void func()
        {
            Console.WriteLine("Base Class");
        }
    }
    public class A : Demo
    {
        public override double Area(double r)
        {
 
            return base.Area(r) * r;
        }
        public new void func()
        {
            Console.WriteLine("Derived Class");
        }
    }
    public class Test
    {
        public static void Main(string[] args)
        {
            A o1 = new A();
            Console.WriteLine(o1.Area(20));
            o1.func();
            Console.ReadLine();
        }
    }
}
Program Explanation

In this C# program, using new keyword we are creating an object ‘o1’ variable for class A. The method func() in the base class and in the derived class give a completely new definition to the same method by preceding it with ‘new’ keyword.

advertisement
advertisement

In Demo class we have created two functions. The Area() function is used for computing an area. Then func() function is used to print the output of the program. Then ‘class A’ inherits the property of Demo class, then compute the area.

Runtime Test Cases
 
8000
Derived Class

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.