Search code examples
c#vb.netambiguity

Inconsistencies in compiler ambiguity errors


In this question, the following class is defined:

public class Program
{
    int n = 0;

    public void Print()
    {
        Console.WriteLine(n);
    }

    public Program()
    {
    }

    public Program(int num = 10)
    {
        n = num;
    }
}

Now, obviously a call to the constructor here using new Program() is ambiguous due to the optional parameter on the second constructor. When reading this its not clear whether n should be initialized with 0 or 10.

However:

Actual reporting of the problem seems inconsistent. Setting up this class and using it I was able to use new Program() in either C#, or VB.Net, and in .Net 4 or .Net 4.5. All tests were done in VS2013.

In the linked question though, the OP actually got the error message when using VB.Net IN .NET 4 and VS2010:

'.ctor' is ambiguous because multiple kinds of members with this name exist in class 'ConsoleApplication2.Program'.

So why is the error there sometimes while at other times the program can be executed successfully?

For reference the value of n when the execution is successful is 0.


Solution

  • Because the VB language changed between versions 10 and 11. In the Version 11 Language Specification, Section 11.8.1. Tie breaking rule 7.9 was added:

    7.9. If M did not use any optional parameter defaults in place of explicit arguments, but N did, then eliminate N from the set.

    (As were rules 7.8 and 7.10, but irrelevant here)