Monday, November 29, 2010

Using Virtual Functions in C sharp.

When you have a function defined in a class which you want to be implemented by the inherited classes, you can use Virtual Function. The Virtual function could be implemented by the inherited classes in their own way and the call to the method is decided at runtime.  

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VirtualFunction
{
    class Animal
    {
        public virtual void FoodHabits()
        {
            Console.WriteLine("Animals have different food habits");
        }
    }
    class Carnivorous : Animal
    {
        public override void FoodHabits()
        {
            Console.WriteLine("the Carnivorous animals eat only meat");
        }
    }
    class Herbivorous : Animal
    {
        public override void FoodHabits()
        {
            Console.WriteLine("The Carnivorous animals eat only plants");
        }
    }
    class Implement
    {
        public void CallFunction(Animal Cr)
        {
            Cr.FoodHabits();
        }
    }
    class ClassMain
    {
        public static void Main()
        {

            Implement Imp = new Implement();
            Carnivorous cn = new Carnivorous();
            Herbivorous hb = new Herbivorous();

            Imp.CallFunction(cn);
            Imp.CallFunction(hb);
            Console.ReadLine();

        }
    }
}

NOTE: - The base class named Animal has a virtual function named FoodHabits. The derived classes Carnivorous and Herbivorous override the method FoodHabits of the base class Animal and implement their own functionality. The method named CallFunction takes and argument of Animal Class and Call FoodHabits () method to, which in turn will call the most apporopriatederived method.

No comments:

Recent Posts