C#: Virtual method

This entry is part 57 of 71 in the series C#

When you declare a method as virtual, you are basically laying the path for it to be overridden.

By default, or if there is no declaration, methods are non-virtual. Only virtual methods can be overridden.

using System;
class Music
{
    public virtual void Play()
    {
        Console.WriteLine("I am virtual and I will be overidden.");
    }
}
class Pop : Music
{
    public override void Play()
    {
        Console.WriteLine("My parent method is a virtual method and so I will be printed out.");
    }
}
class Test
{
    static void Main()
    {
        Pop pop = new Pop();

        pop.Play();
        Console.ReadKey();
    }
}

When you declare a member as virtual method,  this method can be changed by an overriding member in a derived class.

During run time, the program will look for a method in the most derived class for a similar method with the override keyword.

When pop.Play() in line 22 is invoked, the method with the override keyword will be called.

virtual

 

 

Series Navigation<< C#: The is Keyword
C#: Abstract class >>

Leave a comment

Leave a Reply