Why can a structure have two equally visible constructors that can be called with the same exact arguments?
I just stumbled upon something in VB.NET, it looks like it won't be able to compile:
Private Structure SomeStruct
Friend ReadOnly Property Text1 As String
Friend ReadOnly Property Text2 As String
Friend ReadOnly Property Text3 As String
Friend Sub New(text2 As String, Optional text3 As String = Nothing)
Me.New(Nothing, text2, text3)
End Sub
Friend Sub New(text1 As String, text2 As String, Optional text3 As String = Nothing)
Me.Text1 = text1
Me.Text2 = text2
Me.Text3 = text3
End Sub
End Structure
Not only is it possible to compile the above, but it is also possible to compile external code:
Dim structs As SomeStruct() = {New SomeStruct("Argument1", "Argument2")}
In the above line, it seems ambiguous which constructor is executing those two lines. It shouldn't be possible - especially on the one line above, which actually calls the constructor from outside the struct, but it compiles just fine. (I am using VS2015 and .NET 4.5.)
Any decent compiler that allows this will be consistent in which constructor it will match two string arguments from outside code, but why should this be allowed in the first place? Is this a gap in the language definition that leaves different compilers to their own devices (like things like .NET and Java should be good in their absence)? Is it in design language? Is there a uniform rule chosen by Microsoft, or is this just a mistake?
What is the explanation for this?
source to share
It looks like VB is trying to match the number of arguments first, since it calls the parameter constructor 2.
While I think you could say they are ambiguous, there is a way to call the second constructor while leaving the third parameter blank.
New SomeStruct("foo", "bar",) 'Notice the extra comma.
I don't like the idea that this is allowed, but it looks more like VB to me, as there are ways to call the desired constructor.
source to share