Question

Why doesn't the C# compiler get confused about methods that have default arguments?

In the below code SayHello() may refer to:

  • SayHello()
  • SayHello(string arg1 = null)
  • SayHello(string arg1 = null, string arg2 = null)
  • SayHello(string arg1 = null, string arg2 = null, string arg3 = null)

But this code compiles successfully without any ambiguous errors.

class Program
{
    private static void SayHello()
    {
        Console.WriteLine("Hello 1");
        return;
    }

    private static void SayHello(string arg1 = null)
    {
        Console.WriteLine("Hello 2");
        return;
    }

    private static void SayHello(string arg1 = null, string arg2 = null)
    {
        Console.WriteLine("Hello 3");
        return;
    }

    private static void SayHello(string arg1 = null, string arg2 = null, string arg3 = null)
    {
        Console.WriteLine("Hello 3");
        return;
    }

    private static void Main(string[] args)
    {
        SayHello(); // SayHello() invoked, but SayHello(string arg1 = null) not invoked.
        SayHello("arg1");
        SayHello("arg1", "arg2", "arg3");

        // Output is:
        // Hello 1
        // Hello 2
        // Hello 3

        return;
    }
}
Was it helpful?

Solution

The compiler will opt for the method without any optional parameters first. As a result, there is no ambiguity in your code as far as the compiler is concerned.

OTHER TIPS

Why C# compiler doesn't confuse about methods that have default arguments?

This question is not answerable. An answerable question is:

What section of the C# language specification should I read if I want to understand how overload resolution deals with default arguments?

Get a copy of the C# 4 specification; you can download it or buy the annotated paper version. The sections you want to read are 7.5.1 "Argument lists", and 7.5.3 "Overload resolution". In particular see the section 7.5.3.2 "Better function member".

The exact line that describes the behaviour you are seeing is:

If all parameters of Mp have a corresponding argument whereas default arguments need to be substituted for at least one optional parameter in Mq, then Mp is better than Mq.

The compiler has rules (detailed here) to choose the right overload

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top