Method Overloading In C#.NET

What is overloading in C#?

The process of creating more than one method in a class with the same name or creating a method in a derived class with the same name as a method in the base class is called "method overloading". It is a compile time polymorphism.

In C#, we have no need to use any keyword while overloading a method either in the same class or in a derived class.
 
While overloading the methods, a rule to follow is that the overloaded methods must differ either in number of arguments they take or the data type of at least one argument.

Program
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace functionloadingProgram {  
  7.     class class1 {  
  8.         public int Add(int x, int y) {  
  9.             return x + y;  
  10.         }  
  11.         public float Add(int x, float y) {  
  12.             return x + y;  
  13.         }  
  14.     }  
  15.     class class2: class1 {  
  16.         public int Add(int x, int y, int z) {  
  17.             return x + y + z;  
  18.         }  
  19.     }  
  20.     class Program {  
  21.         static void Main(string[] args) {  
  22.             class2 obj = new class2();  
  23.             Console.WriteLine(obj.Add(10, 10));  
  24.             Console.WriteLine(obj.Add(10, 12.1 f));  
  25.             Console.WriteLine(obj.Add(10, 20, 30));  
  26.             Console.ReadLine();  
  27.         }  
  28.     }  
  29. }  
Output

20
22.1
60

In this example, you can observe that there are 3 methods with the name Add() but with different parameters.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now