Virtual keyword in C#

In this article I will explain the concept of virtual keyword in C#.
  • 2885

Introduction

The concept of virtual keyword is very simple in C#. The virtual keyword is used to modify a method, property, event declaration, and allow it to be overridden in a derived class. When we want to override a method of base class to the derived class method then we must be created as virtual method within the base class. When a method declared as virtual in base class, then that method can be defined in base class and it is optional for the derived class to override that method. 

Example

using System;

using System.Collections.Generic;

using System.Text;

namespace virtualsample

{

    class Shape

    {

        protected float R, L, B;

        public virtual float Area()

        {

 

            return 3.14F * R * R;

        }

        public virtual float Circumference()

        {

            return 2 * 3.14F * R;

        }

   }

   class Rectangle : Shape

    {

        public void GetLB()

        {

            Console.Write("Enter  Length  :  ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");

            B = float.Parse(Console.ReadLine());

        }

        public override float Area()

        {

 

            return L * B;

        }

       public override float Circumference()

        {

            return 2 * (L + B);

        }

    }

   class Circle : Shape

    {

        public void GetRadius()

        {

            Console.Write("Enter  Radius  :  ");

            R = float.Parse(Console.ReadLine());

        }

    }

   class MainClass

    {

        static void Main()

        {

            Rectangle R = new Rectangle();

            R.GetLB();

            R.Area();

            Console.WriteLine("Area : {0}", R.Area());

            Console.WriteLine("Circumference : {0}", R.Circumference());

            Console.WriteLine();

            Circle C = new Circle();

            C.GetRadius();

            Console.WriteLine("Area : {0}", C.Area());

            Console.WriteLine("Circumference : {0}", C.Circumference());

            Console.Read();

        }

    }

}

 

The output of the following program

Clipboard170.jpg

© 2019 DotNetHeaven. All rights reserved.