Reputation: 82306
Question:
The below program throws a runtime error (invalid conversion from double) because there is
+ _
followed by a newline and a
+"
In other words, it's
"SomeString" + "someotherstring" ++ "yet another string"
<STAThread()> _
Sub Main()
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder
Dim dt As New DataTable
dt.Columns.Add("oeId", GetType(String))
dt.Columns.Add("ZO_RM_Name", GetType(String))
dt.Columns.Add("ZO_GB_Name", GetType(String))
dt.Columns.Add("gubeg", GetType(DateTime))
dt.Columns.Add("guend", GetType(DateTime))
Dim dr As DataRow = Nothing
For i As Integer = 0 To 10 Step 1
dr = dt.NewRow()
dr("oeId") = "Organization Unit id " + (i * 1000).ToString()
dr("ZO_RM_Name") = "Room " + i.ToString()
dr("ZO_GB_Name") = "Building " + i.ToString()
dr("gubeg") = System.DateTime.Now
dr("guend") = System.DateTime.Now.AddDays(22).AddYears(20).AddHours(2)
dt.Rows.Add(dr)
Next
For Each drThisRow As DataRow In dt.Rows
sb.AppendLine("Organisationseinheit " + drThisRow("oeId").ToString() + _
+" in Raum " + drThisRow("ZO_RM_Name").ToString() + " von Gebäude " + drThisRow("ZO_GB_Name").ToString() _
+ " in der Gültigkeit von " + drThisRow("gubeg").ToString() + " bis " + drThisRow("guend").ToString() + "." _
)
Next
End Sub '' Main ''
One could simplify this problem to this one:
Dim newstring As String = "SomeString" + "someotherstring" + +"yet another string"
It compiles fine, but when the program is run, it throws a runtime error.
Is this a compiler bug ?
Shouldn't it stop me with a compiler error, like invalid syntax ?
Upvotes: 1
Views: 221
Reputation: 391566
The + operator comes in two variants:
a + b
+a
The first one says "take a
and add b
and produce the results". The second one says "take a
with a positive sign".
In this case, the expression is evaluated as a string + a double, because VB.NET, with OPTION STRICT OFF
will think that you want the second operand here as a string, that will be autoconverted to a double at runtime, because you prefixed it with the unary +
operator.
Set OPTION STRICT ON
to make VB.NET be more strict with its typechecking at compiletime, at the expense of you having to write code a bit more specific in some cases.
Upvotes: 4
Reputation: 7280
Try using &
to act as the concatenation operator in vb.net, this will cause a compile error without enabling Option Strict
. I think what is happening is that due to there being no content between the operators it is using the second +
as a sign for a number (e.g. +1
). Due to VB default behaviour of implicitly converting it tries convert the string literal to a number.
Using Option Strict On
will cause a compiler error to be displayed.
Upvotes: 2