C# Virtual method

C# virtual keyword enables us to make a method, property, indexer, or an event virtual. It also allows and gives an indication to the derived class, to override virtual members of the base class.

Following is an example of a virtual method.

public virtual void PrintName()
{
    //Method body
}

By default class methods are non-virtual. A derived class can't override the method of a base class till the method is not marked as virtual.

Following is incorrect. If you will try to do so, you will get a compiler error stating can't override inherited member because it is not marked virtual, abstract or override

public class StudentBase
{
    public void Print()
    {
        //Print body
    }
}
 
public class Student : StudentBase
{
    public override void Print() //Not possible
    {
        Console.WriteLine("Hello");
    }
}

In C# a derived class can change the implementation of a base class virtual method.

Example

Try It
public static void Main()
{
    Student student = new Student();
    student.FirstName = "Jhon";
    student.LastName = "Doe";
    student.Print();
}
public class StudentBase
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
 
    public virtual void Print()
    {
        Console.WriteLine("Student first name is :{0}", this.FirstName);
    }
}
 
public class Student : StudentBase
{
    public override void Print() 
    {
        Console.WriteLine("Student first name is :{0} and last name is {1}", this.FirstName, this.LastName);
    }
}

In C# it is not possible to make a method virtual if it has any of the modifiers from following.

  • static,
  • abstract,
  • private,
  • override

Let's learn about method overloading in the next section.