Home  >  Article  >  Backend Development  >  What is overloading in C#?

What is overloading in C#?

WBOY
WBOYforward
2023-09-06 22:17:02786browse

What is overloading in C#?

C# provides two techniques to achieve static polymorphism -

  • Function overloading
  • Operator overloading

Function overloading

Two or more methods with the same name but different parameters are our function overloading in C#.

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

Suppose you have a function that prints the 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 example shows how to implement function overloading -

Example

Live demonstration

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, key A literal operator is followed by the symbol of the defined operator.

The following shows which operators can be overloaded and which operators can be overloaded but not overloaded-

##456
Sr.No Operation Symbol and description
1 , - , !, ~, , --

These unary operators take one operand and can be overloaded.

2 , -, *, /, %

These binary operators Takes an operand and can be overloaded.

3 ==、!=、、=

Comparison operators can be overloaded.

&&, ||Conditional logical operators cannot be overloaded directly.

=、-=、*=、/=、%= Assignment operators cannot be overloaded.

=, ., ?:, -These operators cannot be overloaded

The above is the detailed content of What is overloading in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete