Virtual Methods in C#.NET with example
When you want to allow a derived class to override a method of the base class, within the base class method must be created as virtual method and within the derived class method must be created using the keyword override.
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.
When it needs same definition as base class, then no need to override the method and if it needs different definition than provided by base class then it must override the method.
Method overriding also provides more than one form for a method. Hence it is also an example for polymorphism.
The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as virtual in Shape class.
using System;
namespace ProgramCall
{
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();
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();
}
}
}
Output
Enter Length : 10
Enter Breadth : 20
Area : 200
Circumference : 60
Enter Radius : 25
Area : 1962.5
Circumference : 157