Overriding vs. Overloading Functions

Introduction

 

When it comes to overriding versus overloading functions in C#, it is important to know the difference between the two concepts. In this article, I will help to explain that.
 

Overriding

Let's assume I have a function in the parent class and this function was used in all child classes. One of the child classes needs to change the implementation for the parent function, so the best practice here is to use the overriding function in child class.

Please see the following example:
  1. class masterClass  
  2.   
  3. {  
  4.   
  5.  public virtual void ShowInfo(int i)  
  6.   
  7.  {  
  8.   System.Console.WriteLine("masterClass has value " + i);  
  9.  }  
  10.   
  11. }  
  12.   
  13. class childClass: masterClass  
  14.   
  15. {  
  16.  // Overidding Function.  
  17.  public override void ShowInfo(int i)  
  18.   
  19.  {  
  20.   // Change the implementation here …  
  21.   int y = 0;  
  22.   y = i + 1;  
  23.   System.Console.WriteLine("childClass has value " + y);  
  24.  }  
  25.   
  26. }  

To recap, overriding is when we have more than one function with the same method name, number and types of parameters as the function in the parent class, but the implementation in the child class is different.

Overloading

Let's assume I have a function in the class and I need to change the implementation of it by the type or number of parameters. The best practice here is to use overloading.

Please see the following example:

  1. Class mainClass {  
  2.  int Calculate(int x, int y) {  
  3.   return x + y;  
  4.  }  
  5.  int Calculate(int x, int y, int z) {  
  6.   return x + y + z;  
  7.  }  
  8. }  

To recap, when we have more than one function in the same class with the same name, but there are differences in the type or number of parameters, this is called Overloading.


Important Note: Overloading functions returns the same data type.
 
Next Recommended Reading Override ToString() Method in C#