Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
10.6.2 Compound Assignment Statements

10.6.2 Compound Assignment Statements

Visual Studio .NET 2003

A compound assignment statement takes the form V OP= E (where OP is a valid binary operator). The expression on the left side of the assignment operator must be classified as a variable or property access, while the expression on the right side of the assignment operator must be classified as a value. The compound assignment statement is equivalent to the statement V = V OP E with the difference that the variable on the left side of the compound assignment operator is only evaluated once. The following example demonstrates this difference:

Module Test
    Function GetIndex() As Integer
        Console.WriteLine("Getting index")
        Return 1
    End Function

    Sub Main()
        Dim a(2) As Integer

        Console.WriteLine("Simple assignment")
        a(GetIndex()) = a(GetIndex()) + 1

        Console.WriteLine("Compound assignment")
        a(GetIndex()) += 1
    End Sub
End Module

The expression a(GetIndex()) is evaluated twice for simple assignment but only once for compound assignment, so the code prints:

Simple assignment
Getting index
Getting index
Compound assignment
Getting index

The rule for predefined operators is simply that V OP= E is permitted if both V OP E and V = E are permitted. Thus, in the following example, the reason for each error is that a corresponding simple assignment would also have been an error.

Option Strict On
Module Test
    Private b As Byte = 0
    Private ch As Char = ControlChars.NullChar
    Private i As Integer = 0
    Sub Main()
        b += 1 ' This is allowed.
        b += 1000 ' Error; b = 1000 is not permitted.
        b += i ' Error, b = I is not permitted.
        b += CByte(i) ' This is allowed.
        ch += 1 ' Error, ch = 1 is not permitted.
        ch += ChrW(1) ' This is allowed.
    End Sub
End Module
CompoundAssignmentStatement ::=
   Expression CompoundBinaryOperator = Expression StatementTerminator
CompoundBinaryOperator ::= ^ | * | / | \ | + | - | & | < < | > >

See Also

10.6.1 Regular Assignment Statements | 10.6.3 Mid Assignment Statement | 10.6 Assignment Statements | Assignment Operators (Visual Basic Language Reference)

© 2015 Microsoft