Virtual keywords use in C#


Introduction:

A virtual keyword is used to modify a method property  event declaration and allow to be overridden in a derived class. in this program the class dimensions contain the two coordinates a,b and the area()virtual method.diffrent shape class such as circle cylinder and sphere inherit the dimensions class and the surface area is calculated for each figure. 

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class TestClass
{
    public class Dimensions
    {
        public const double PI = Math.PI;
        protected double a, b;
        public Dimensions()

        {
        }
         public Dimensions(double a, double b)
        {
            this.a = a;
            this.b = b;
        }

        public virtual double Area()
        {
            return a*b;
        }
    }
    public class Circle : Dimensions
    {
        public Circle(double r)
            : base(r, 0)
        {
        }

        public override double Area()
        {
            return PI * a * b;
        }
    }

    class Sphere : Dimensions
    {
        public Sphere(double r)
            : base(r, 0)
        {
        }

        public override double Area()
        {
            return 100 * PI * a * a;
        }
    }

    class Cylinder : Dimension

    {
        public Cylinder(double r, double h)
            : base(r, h)
        {
        }

        public override double Area()
        {
            return 2 * PI * a * a + 8 * PI * a * b;
        }
    }

    static void Main()
    {
        double r = 10.0, h = 8.0;
        Dimensions c = new Circle(r);
        Dimensions s = new Sphere(r);
        Dimensions l = new Cylinder(r, h);
        
        Console.WriteLine("Area of Circle   = {0:F2}", c.Area());
        Console.WriteLine("Area of Sphere   = {0:F2}", s.Area());
        Console.WriteLine("Area of Cylinder = {0:F2}", 1.Area());
    }
}
Output:
dimenssion.gif

Thank you. if U have any Suggestions and Comments about my blog, Plz let me know.

 

Ebook Download
View all
Learn
View all