Posterous theme by Cory Watilo

The difference between the + and & operators in VB.NET

It’s quote common to see VB.NET code where the author does not know about the distinction between the two concatenation operators. While the code probably compiles and executes just fine one of the operators leaves you vulnerable to unexpected errors if, for example changes are made to the code.


Take a look at the following code snippet for a second and see if you can spot why the second concatenation will throw and exception.


Dim value As Double = 10DDim correct As String = _   "The value is " & value & ". Pretty cool, huh?"Dim incorrect As String = _   "The value is " + value + ". Pretty cool, huh?"

The exception which is thrown is “Conversion from string "The value is " to type 'Double' is not valid.”. Huh? We’re concatenating into a string aren’t we? So why do we get an InvalidCastException that tells us it wasn’t able to cast to a double?


The short version is that in VB.NET the & is known as the string concatenation operator, thus expects both the left hand and right hand side of the operator to be strings and if they’re not it will try to perform a cast to a string before performing the concatenation.


The + operator tries to add two values together and its behaviour on what to do, if mixed data types are involved, is controlled by far more complex logic (see the link below for the full story) and environmental variables such as the Option Strict settings.


& Operator

http://msdn.microsoft.com/en-us/library/wfx50zyk.aspx


+ Operator

http://msdn.microsoft.com/en-us/library/9c5t70w2.aspx