What is the Virtual Method in C#?

Virtual method in C#

A Virtual is a Keyword, used to modify a method and properties. It has a special privilege to override the base method in the derived class. A virtual method can have an implementation on both the base class and the derived class and in the derived class it is optional to override the base class virtual methods.

How do we define the Virtual method in the base class?

   public class EmployeeBenefits
   {
        int days = 30;
        //Later this property can be modified as per the requirement.
        public virtual int dayPay { get; set; } = 1500;
        public virtual int Salary()
        {
            return days * dayPay;
        }

    }

What is the use of the Virtual method?

  • In object-oriented programming, one of the most useful features is polymorphism. With the help of a virtual method, overriding implementation in the derived class can archive the polymorphism.
  • In the derived class, it is not mandatory to override the functionality.
  • The virtual method has an implementation in the base class, and later, if required, it can be overridden.
  • A virtual method may or may not have a return type.

Code Example

    public class EmployeeBenefits
    {
        int days = 30;

        //Later this property can be modified as per the requirement. 
        public virtual int dayPay { get; set; } = 1500; 
        public virtual int Salary()
        {
            return days * dayPay;
        }
    }


    public class ContractEmployee: EmployeeBenefits 
    {
        public override int Salary()
        {
            return base. Salary()+500;
        }
    }

The ContractEmployee Class is inherited from the EmployeeBenefits, and It overrides the base class Salary method and is modified.


Similar Articles