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 ?
The + operator comes in two variants:
a + b+aThe first one says “take
aand addband produce the results”. The second one says “takeawith a positive sign”.In this case, the expression is evaluated as a string + a double, because VB.NET, with
OPTION STRICT OFFwill 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 ONto 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.