Virtual Methods in C#

In simplest word, a virtual method in C# is a method that can have different implementation in parent and child classes. Virtual methods are used to achieve type base polymorphism where the usage of the function is different from its implementation.

Virtual methods are created via virtual keyword, while the child classes that implement their own implementation of the method override this virtual method via override keyword. Have a look at the following example to understand this concept.

using System;

namespace CSharpTutorials {

    public abstract class Vehicle {

        public virtual void VirtualMethod() {
            Console.WriteLine("This is a parent class method");
        }

    }

    public class Car : Vehicle {

        public override void VirtualMethod() {
            Console.WriteLine("This is an overriden child class method");
        }
    }

    public class Truck : Vehicle {
     
    }

    class Tutorial {
        static void Main(string[] args) {
            // Creating objects of car and truck class
            Car car = new Car();
            Truck truck = new Truck();

            car.VirtualMethod();
            truck.VirtualMethod();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code, a virtual method named VirtualMethod has been define inside the parent Vehicle class. It displays a message which reads that this is the method in parent class. The Car and Truck class inherit this Vehicle class. Car class overrides the parent class virtual method and provides its own implementation while the Truck doesn’t override the VirtualMethod of the vehicle class.

Now, if VirtualMethod is called from the object of the Car class the run time will check if the Car class has an overriden version of the VirtualMethod method? If yes then call the VirtualMethod from the Car class. On the other hand if the VirtualMethod is called from the object of the Truck class the .net runtime will call the VirtualMethod method of the parent Vehicle class since Truck class doesn’t contain an overridden implementation of the method.

<<< Polymorphism in C#C# Abstract class and abstract method >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .