Virtual Method in C#.

Virtual method is a method that can be overridden in derived class. It can have implementaion in a base class, though. Let’s see the example.

namespace CsharpConsoleApplication
{
    class A
    {
        public virtual void G() { Console.WriteLine("A.G"); }
    }
    class B : A
    {
        public override void G() { Console.WriteLine("B.G"); }
    }
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B();
            A a = b;
            a.G(); // "B.G"
            b.G(); // "B.G"
        }
    }
}

In this example we override method G() of class A, since it is marked with virtual keyword and we use overrideĀ keyword in class B.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this