Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am replicating a situation that I am facing.

Let's say we have an assembly, with C# class as:

public class Program
{
    int n = 0;

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

    public Program()
    {
    }

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

We refer the above assembly in VB.NET project and trying to create an instance of the Program class:

Module Module1 
    Sub Main()
        Dim p As New Program()
        p.Print()
        p = New Program(20)
        p.Print()
        Console.ReadLine()
    End Sub
End Module

The VB.NET project is not compiling, giving error:

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

From the error message we can see the the VB.NET compiler is not sure which constructor to call - as one constructor is parameterless and other with one optional parameter. This issue is occurring in VS2010/.NET 4 and not in VS2012/.NET 4.5. Also in C# it is not givng any issues, it successfully compiles and runs the code of object initiaization of Program class.

Is there a way we can create Program class' instance in VB.NET + VS2010/.NET 4 without changing the constructors ?

like image 389
Brij Avatar asked Feb 20 '14 10:02

Brij


1 Answers

The problem is with the definitions of your constructors in the Program class

Because the argument to the second is optional, then both are candidates when calling using New Program(). This creates the ambiguity.

Instead, define your constructors using this sort of pattern:

public Program()
    : this(10)
{
}

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

or just the single constructor:

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

(Personally I prefer the first of these).

like image 124
Jon Egerton Avatar answered Sep 22 '22 01:09

Jon Egerton