Visual Basic has always had the simple assignment operator =. Visual Basic .NET added several new assignment operators to handle some common statements where a value was set equal to itself combined with some other value. For example, the following two statements both add the value 10 to the variable iterations:
iterations = iterations + 10 ' Original syntax.
iterations += 10 ' New syntax.
All the other assignment operators work similarly by adding an equals sign to an arithmetic operator. For example, the statement A ^= B is equivalent to A = A ^ B.
You can still use the original syntax if you like. However, the new syntax sometimes gives you better performance. If the left-hand side of the assignment is not a simple variable, Visual Basic may be able to save time by evaluating it only once. For example, the following code adds 0.1 to a customer order’s discount value. By using +=, the code allows Visual Basic to find the location of this value only once.
Customers(cust_num).Orders(order_num).Discount += 0.1
The complete list of assignment operators is: =, ^=, *=, /=, =, +=, -=, &=, <<=, and >>=.
If you have Option Strict set to On, the variables must have the appropriate data types. For example, /= returns a Double, so you cannot use that operator with an Integer, as in the following code:
Dim i As Integer = 100
i /= 2 ' Not allowed.
To perform this operation, you must explicitly convert the result into an Integer, as shown in the following statement:
i = CInt(i / 2)
This makes sense because you are trying to assign the value of floating-point division to an Integer. It’s less obvious why the following code is also illegal. Here the code is trying to assign an Integer result to a Single variable, so you might think it should work. After all, an Integer value will fit in a Single variable.
Dim x As Single
x = 10 ' Not allowed.
The problem isn’t in the assignment but in performing the calculation. The following statement is equivalent to the previous one, and it is also illegal:
x = x 10 ' Not allowed.
The problem with both of these statements is that the operator takes as arguments two Integers. If Option Strict is on, the program will not automatically convert a floating-point variable into an Integer for the operator. To make this statement work, you must manually convert the variable into an Integer data type, as shown in the following example:
x = CLng(x) 10 ' Allowed.
The += and &= operators both combine strings but &= is less ambiguous, so you should use it whenever possible. It may also give you better performance because it explicitly tells Visual Basic that the operands are strings.