C Sharp Method Overriding

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Method Overriding

If derived class defines same method as defined in its base class, it is known as method overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the method which is already provided by its base class.

To perform method overriding in C#, you need to use virtual keyword with base class method and override keyword with derived class method.

C# Method Overriding Example

Let's see a simple example of method overriding in C#. In this example, we are overriding the eat() method by the help of override keyword.

  1. using System;  
  2. public class Animal{  
  3.     public virtual void eat(){  
  4.         Console.WriteLine("Eating...");  
  5.     }  
  6. }  
  7. public class Dog: Animal  
  8. {  
  9.     public override void eat()  
  10.     {  
  11.         Console.WriteLine("Eating bread...");  
  12.     }  
  13. }  
  14. public class TestOverriding  
  15. {  
  16.     public static void Main()  
  17.     {  
  18.         Dog d = new Dog();  
  19.         d.eat();  
  20.     }  
  21. }  

Output:

Eating bread...