Using + or & for concatenating strings - and an implicit cast

F

FB's .NET Dev PC

Interesting note, the code below as is will attempt to cast what is clearly
indicated as a string into a double. This is becuase the use of + as a
concatenation operator. The error message generated is included with the
code. Use & instead and it works.



Dim pstrSend As String = ""

'ActionCode 1 and 2 are type BYTE, Msg is a byVal string parameter



pstrSend = Chr(ActionCode1) + Chr(ActionCode2) + Msg + &HFF & vbCr

'write and flush

objSocketWriter.Write(pstrSend)

objSocketWriter.Flush()

End Function



An unhandled exception of type 'System.InvalidCastException' occurred in
microsoft.visualbasic.dll

Additional information: Cast from string "cThis is a longer test message" to
type 'Double' is not valid.



System.InvalidCastException: Cast from string "cThis is a longer test
message" to type 'Double' is not valid. ---> System.FormatException: Input
string was not in a correct format.
 
O

One Handed Man \( OHM - Terry Burns \)

Now try it with OPTION Strict = ON and see if it compiles

--
OHM ( Terry Burns ) * Use the following to email me *

Dim ch() As Char = "ufssz/cvsotAhsfbuTpmvujpotXjui/OFU".ToCharArray()
For i As Int32 = 0 To ch.Length - 1
ch(i) = Convert.ToChar(Convert.ToInt16(ch(i)) - 1)
Next
Process.Start("mailto:" & New String(ch))
 
J

Jay B. Harlow [MVP - Outlook]

FB,
pstrSend = Chr(ActionCode1) + Chr(ActionCode2) + Msg + &HFF & vbCr
&HFF is an "number", Msg needs to be converted to a number so that the two
numbers can be added together.

Which is why I use & for concatenating strings, the only implicit
conversions are to string.

Also if you use Option Strict On, you will get a compile error instead of a
runtime error.

Hope this helps
Jay
 
H

Herfried K. Wagner [MVP]

FB's .NET Dev PC said:
Interesting note, the code below as is will attempt to cast what is
clearly indicated as a string into a double. This is becuase the use of +
as a concatenation operator. The error message generated is included with
the code. Use & instead and it works.

Add 'Option Strict On' on top of your source file and "try again".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top