Home > Backend Development > C#.Net Tutorial > Overloaded methods and ambiguity in C#

Overloaded methods and ambiguity in C#

WBOY
Release: 2023-09-06 08:45:10
forward
794 people have browsed it

C# 中的重载方法和歧义

Method overloading allows you to have multiple definitions of the same function name in the same scope. Function definitions must differ in the type and/or number of parameters in the parameter list.

Let's look at an example. Here, the call goes to a method with a single parameter -

Example

using System;

class Student {
   static void DisplayMarks(int marks1 = 90) {
      Console.WriteLine("Method with one parameter!");
   }

   static void DisplayMarks(int marks1, int marks2 = 95) {
      Console.WriteLine("Method with two parameters!");
   }

   static void Main() {
      DisplayMarks(97);
   }
}
Copy after login

Now let's see what causes an ambiguous call. The confusion here is that the second method requires two default parameters, while the first method requires one parameter to be defaulted. This creates ambiguity.

Example

using System;

class Student {
   static void DisplayMarks(int marks1 = 90, int marks2 = 80) {
      Console.WriteLine("Method with two parameters!");
   }

   static void DisplayMarks(int marks1, int marks2 = 80, marks3 = 98) {
      Console.WriteLine("Method with three parameters!");
   }

   static void Main() {
      DisplayMarks(80);
   }
}
Copy after login

The above is the detailed content of Overloaded methods and ambiguity in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template