Question

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.

Was it helpful?

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)

OTHER TIPS

For VS2012 and VS2013 is defined:

Overload Resolution

Use of named and optional arguments affects overload resolution in the following ways:

  • A method, indexer, or constructor is a candidate for execution if each of its parameters either is optional or corresponds, by name or by position, to a single argument in the calling statement, and that argument can be converted to the type of the parameter.
  • If more than one candidate is found, overload resolution rules for preferred conversions are applied to the arguments that are explicitly specified. Omitted arguments for optional parameters are ignored.
  • If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

Source

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