Visual Basic .NET/Assignation and comparison operators


The "=" operator is used for assignment. The operator also serves as a comparison operator (see Comparison).

  • To set values:
  x = 7     ' x is now seven; in math terms we could say "let x = 7"
  x = -1294
  x = "example"

You can use variables in the equal operator, as well.

  Dim x As Integer
  x = 4  ' Anywhere we use x, 4 will be used.


The "=" operator is used for comparison. The operator also serves as a assignation operator (see Assignment).

  • To compare values:
  If 4 = 9 Then       ' This code will never happen:
    End  ' Exit the program.
  End If
  If 1234 = 1234 Then ' This code will always be run after the check:
    MessageBox.Show("Wow!  1234 is the same as 1234.") 
      ' Create a box in the center of the screen.
  End If

You can use variables in the equal operator, as well.

  If x = 4 Then
    MessageBox.Show("x is four.")
  End If

Let's try a slightly more advanced operation.

  MessageBox.Show("Seven equals two is " & (7 = 2) & ".")
  ' The parentheses are used because otherwise, by order of operations
  ' (equals is processed last), it would be comparing "Seven equals two is 7" and "2.".
  ' Note here that the & operator appends to the string.  We will talk about this later.
  '  The result of this should be a message box popping up saying "Seven equals two is
  '   False."   This is because (7 = 2) will return False anywhere you put it.  In the
  '   same sense, (7 = 7) will return True:
  MessageBox.Show("Seven equals seven is " & (7 = 7) & ".")

You will get an error if you try to assign a constant or a literal a value, such as 7 = 2. You can compare 7 and 2, but the answer will always be False.

In the case of two equal operators appearing in a statement, such as

  Dim x As Boolean
  x = 2 = 7

The second equal operator will be processed first, comparing 2 and 7, giving a False. Then the first equal operator will be processed, assigning False to x.

More Comparison OperatorsEdit

 (x < y)  (x > y)  (x <> y)  (x <= y)  (x >= y)

(x less than y), (x more than y), (x not equal to y), (x less than or equal y) & (x greater than or equal to y)

Note the way round the operators are on the last two, putting them the other way round is not valid.

Last modified on 30 June 2013, at 20:22