Search code examples
c#ambiguousdefault-parameters

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


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;
    }
}

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.