if a method contains an overload with optional parameters which overload is called when parameters are supplied?

When method overloading involves optional parameters, the compiler gives preference to the method with no optional parameters involved first. For example, consider the below method overload definitions:

public void Add(int a, int b, int c = 5)
{
  Console.WriteLine($"{a} + {b} + {c} = {a + b + c}");
}

public void Add(int a, int b)
{
  Console.WriteLine($"{a} + {b} = {a + b}");
}

The outputs when called with the below arguments is as below:

p.Add(2, 3, 6); // 2 + 3 + 6 = 11
p.Add(4, 5); // 4 + 5 = 9

In the second call, even though the overload with optional parameter c is a valid match the compiler picks up the overload with two arguments for the execution. This is because the compiler gives the priority to the variable arguments over the substitutable constants.

C# Concepts Posted Jun 19, 2021

You can now show your support. 😊

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept