
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Overloaded method and ambiguity in C#
With method overloading, you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.
Let us see an example. In this the call would go to the 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); } }
Now let us see what creates an ambiguous call. Here the confusion is that the second method would need two arguments as defaults, whereas the first methid needs one argument 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); } }
- Related Articles
- Method Overloading and Ambiguity in Varargs in Java
- What are the different ways for a method to be overloaded in C#?
- Pass long parameter to an overloaded method in Java
- What are overloaded indexers in C#?
- Can main() be overloaded in C++?
- Functions that can’t be overloaded in C++
- Operators that cannot be overloaded in C++
- Functions that cannot be overloaded in C++
- If I change the return type, will the method gets overloaded in java?
- Hiding of all overloaded methods in base class in C++
- What do you mean by ambiguity in grammar in TOC?
- Use overloaded methods to print array of different types in Java
- Difference between Method Overriding and Method Hiding in C#
- How to implement Python __lt__ __gt__ custom (overloaded) operators?
- Difference between == and .Equals method in c#

Advertisements