method hiding

If we use the same signature of the method in both parent and child class, and do not use virtual and override keywords respectively, then the method of the child class will “hide” the method of the parent class. To avoid this, it is always recommended to use “new” keyword with the method of the child class otherwise there will be a compiler warning.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;


namespace ConsoleApplication6
{
    class BaseClass
    {
        public void MyMethod()
        {
            Console.WriteLine("This is base class virtual method");
        }

    }

    class ChildClass : BaseClass
    {
        
        public new void MyMethod()
        {           
            Console.WriteLine("This is overridden method");
        }
    }

    
    class Program
    {
        static void Main(string[] args)
        {
            ChildClass c = new ChildClass();         
            c.MyMethod();          
        }   
    }
}

 

Add a Comment

Your email address will not be published. Required fields are marked *