Virtual methods

When a method in a class is declared as “virtual” we can “override” the method in the child class. The following is an example:

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


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

        }

    }

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

    
    class Program
    {
        static void Main(string[] args)
        {
          //  BaseClass b = new BaseClass();
          //  b.MyMethod();

            ChildClass c = new ChildClass();
            //  c.MyChildMethod();
            c.MyMethod();
        }        
        
        
    }
}

 

Tags:

Add a Comment

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