virtual members

A virtual member can be overriden by its subclasses.

A virtual member is marked by the virtual keyword.

A virtual feature can be a method, a property, an indexer or an event.

The following code shows how to use the virtual method to provide the different implementation of the Area.


using System;

class Shape{
  public virtual double Area{
     get{
        return 0;
     }
  }
}


class Rectangle:Shape{
   public int width;
   public int height;
   
   public override double Area{
      get{
         return width * height;
      }
   }
}

class Circle:Shape{
   public int radius;
   
   public override double Area{
      get{
         return 3.14 * radius * radius;
      }
   }
}


class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        r.width = 4;
        r.height = 5;
        Circle c = new Circle();
        c.radius = 6;
        Console.WriteLine(r.Area);
        Console.WriteLine(c.Area);

    }
}

The output:


20
113.04

C# requires that the virtual and override must have the same signature, accessor and return type.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.