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.

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.

Default image
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply