Archive

Posts Tagged ‘reminders’

What about the Virtual Keyword in C#

January 28th, 2010 No comments

What confuses sometimes is the use of virtual keyword, so let’s keep some notes in order to remember it.

Definition
The virtual keyword is used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class.

Have in mind
You cannot use the virtual modifier with the following modifiers: static, abstract, override.

How to use it
A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

When to use it
When you want to support polymorphism. When objects derive from a common class, having some common behavior but there are some small differences at the implementation of each object’s behavior.

Examples

using System;
class TestVirtual
{
   public class Shape
   {
      public const double pi = Math.PI;
      protected double x, y;
      public Shape() { }
      public Shape (double x, double y)
      {
         this.x = x;
         this.y = y;
      }

      //This method can be overriden
      public virtual double Area()
      {
         return x*y;
      }
   }

   public class Circle: Shape
   {
      public Circle(double r): base(r, 0)
      {
      }

     // This method is being overriden
      public override double Area()
      {
         return pi * x * x;
      }
   }

	public class Rectangle: Shape
	{
		public Rectangle(double x, double y): base(x, y){}
	}

   public static void Main()
   {
      double r = 3.0, h = 5.0;
      Shape c = new Circle(r);
      Shape s = new Rectangle(r, h);

      // Display results:
      Console.WriteLine("Area of Circle   = {0:F2}", c.Area());
      Console.WriteLine("Area of Rectangle   = {0:F2}", s.Area());
   }
}

Results
Area of Circle: 28.27
Area of Rectangle: 15

Categories: C# Tags: , ,