What is overloading in C#?


C# provides two techniques to implement static polymorphism −

  • Function overloading
  • Operator overloading

Function Overloading

Two or more than two methods having the same name but different parameters is what we call function overloading in C#.

Function overloading in C# can be performed by changing the number of arguments and the data type of the arguments.

Let’s say you have a function that prints multiplication of numbers, then our overloaded methods will have the same name but different number of arguments −

public static int mulDisplay(int one, int two) { }
public static int mulDisplay(int one, int two, int three) { }
public static int mulDisplay(int one, int two, int three, int four) { }

The following is an example showing how to implement function overloading −

Example

 Live Demo

using System;
public class Demo {
   public static int mulDisplay(int one, int two) {
      return one * two;
   }

   public static int mulDisplay(int one, int two, int three) {
      return one * two * three;
   }
   
   public static int mulDisplay(int one, int two, int three, int four) {
      return one * two * three * four;
   }
}

public class Program {
   public static void Main() {
      Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15));
      Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20));
      Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7));
   }
}

Output

Multiplication of two numbers: 150
Multiplication of three numbers: 2080
Multiplication of four numbers: 1470

Operator Overloading

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.

The following shows which operators can be overloaded and which you cannot overload −

Sr.NoOperator & Description
1+, -, !, ~, ++, --
These unary operators take one operand and can be overloaded.
2+, -, *, /, %
These binary operators take one operand and can be overloaded.
3==, !=, <, >, <=, >=
The comparison operators can be overloaded.
4&&, ||
The conditional logical operators cannot be overloaded directly.
5+=, -=, *=, /=, %=
The assignment operators cannot be overloaded.
6=, ., ?:, -<, new, is, sizeof, typeof
These operators cannot be overloaded

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements