VB.Net oddity of the day – Assignment/Comparison operator


On my current project I’m forced to code in VB.Net.  Normally I’m pretty open to other languages, but VB.Net is irritating (more so than VB6 in my opinion).  The language syntax is riddled with ambiguity (at least for a c-type guy like myself) and moving from c# to VB can be confusing.

Here’s my latest beef with VB.Net.  There’s only one operator for assignment and comparisons.  As a result, the compiler handles evaluation of the the language syntax in a subtle, but irritating way.

Here’s some code to illustrate my point, I had something like this in my program:


</FONT>Dim oldValue, currentValue As Integer</P>

oldValue = currentValue = 2


In C# this is cut and dry.  The value 2 would be assigned to currentValue and the side effect would be the value assigned, or 2.  I’ve long been in the habit of using assignment side effects in C#, but VB looks at this differently.  In VB, the value 2 is assigned to currentValue, but the side effect is the comparison of the two values.  In this case, currentValue initializes to 0, so the expression evaluates to false (or 0).  Therefore, oldValue now equals 0.


Now, if I did this:


</FONT>Dim oldValue, currentValue As Integer</P>

currentValue = 2


oldValue = currentValue = 2


When the statement is evaluated, it will first evaluate the expression currentValue = 2.  2 will be assigned to currentValue and the side effect will be the comparison of currentValue to the assigned value, 2.  They are equal, so true will be returned and converted from bool to int as the non-zero value -1.


It’s no biggy, just annoying.

CLOBbered again!