06 Feb 2024




Beginner

In C#, both virtual and override are keywords used in the context of method overriding, a fundamental concept in object-oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Here's the difference between virtual and override:

  1. virtual keyword:

    • When you declare a method with the virtual keyword in the base class, you indicate that the method can be overridden by derived classes.
    • The virtual keyword allows the method in the base class to be redefined in derived classes.
    • Methods marked as virtual provide a default implementation in the base class, but derived classes can choose to override this method with their own implementation.
    • Example:
      public class BaseClass
      {
          public virtual void MyMethod()
          {
              Console.WriteLine("Base class implementation");
          }
      }
      
  2. override keyword:

    • When you override a method in a derived class, you use the override keyword to indicate that you are providing a new implementation for a method that is already defined in the base class.
    • You must use the override keyword in the derived class to indicate that you are intentionally overriding a virtual method from the base class.
    • The method signature (name, return type, and parameters) in the derived class must match exactly with the method signature in the base class.
    • Example:
      public class DerivedClass : BaseClass
      {
          public override void MyMethod()
          {
              Console.WriteLine("Derived class implementation");
          }
      }
      

In summary, virtual allows a method in a base class to be overridden in derived classes, while override is used in the derived class to indicate that it is intentionally overriding a method from the base class. Together, these keywords facilitate polymorphism and dynamic method invocation in object-oriented programming.

c-sharp
virtual
override
difference