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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace functionloadingProgram {
- class class1 {
- public int Add(int x, int y) {
- return x + y;
- }
- public float Add(int x, float y) {
- return x + y;
- }
- }
- class class2: class1 {
- public int Add(int x, int y, int z) {
- return x + y + z;
- }
- }
- class Program {
- static void Main(string[] args) {
- class2 obj = new class2();
- Console.WriteLine(obj.Add(10, 10));
- Console.WriteLine(obj.Add(10, 12.1 f));
- Console.WriteLine(obj.Add(10, 20, 30));
- Console.ReadLine();
- }
- }
- }
Output
20
22.1
60
In this example, you can observe that there are 3 methods with the name Add() but with different parameters.