You are on page 1of 10

An operator is a code element that performs an operation on one or more code

elements that hold values. Value elements include variables, constants, literals, properties,
returns from Function and Operator procedures, and expressions.
An expression is a series of value elements combined with operators, which
yields a new value. The operators act on the value elements by performing calculations,
comparisons, or other operations.
A statement in Visual Basic is a complete instruction that can contain keywords,
operators, variables, constants, and expressions. All statements fall into one of two
categories: declaration statements, which name a variable, constant, or procedure and can
also specify a data type; or executable statements, which initiate actions.

Reserved Keywords
The following keywords are reserved, which means you cannot use them as names for
your programming elements such as variables or procedures.
AddHandler AddressOf Alias And
AndAlso As Boolean ByRef
Byte ByVal Call Case
Catch CBool CByte CChar
CDate CDec CDbl Char
CInt Class CLng CObj
Const Continue CSByte CShort
CSng CStr CType CUInt
CULng CUShort Date Decimal
Declare Default Delegate Dim
DirectCast Do Double Each
Else ElseIf End EndIf
Enum Erase Error Event
Exit False Finally For
Friend Function Get GetType
Global GoSub GoTo Handles
If Implements Imports In
Inherits Integer Interface Is
IsNot Let Lib Like
Long Loop Me Mod
Module MustInherit MustOverride MyBase
MyClass Namespace Narrowing New
Next Not Nothing NotInheritable
NotOverridable Object Of On
Operator Option Optional Or
OrElse Overloads Overridable Overrides
ParamArray Partial Private Property
Protected Public RaiseEvent ReadOnly
ReDim REM RemoveHandler Resume
Return SByte Select Set

Page 1 of 10
Shadows Shared Short Single
Static Step Stop String
Structure Sub SyncLock Then
Throw To True Try
TryCast TypeOf Variant Wend
UInteger ULong UShort Using
When While Widening With
WithEvents WriteOnly Xor #Const
#Else #ElseIf #End #If

Types of Operators
The following are the arithmetic operators defined in Visual Basic.
^ Operator
* Operator
/ Operator
\ Operator
Mod Operator
+ Operator (unary and binary)
- Operator (unary and binary)

The following are the assignment operators defined in Visual Basic.


= Operator
^= Operator
*= Operator
/= Operator
\= Operator
+= Operator
-= Operator
&= Operator

The following are the comparison operators defined in Visual Basic.


< operator
<= operator
> operator
>= operator
= operator
<> operator

The following are the concatenation operators defined in Visual Basic.


& Operator
+ Operator

The following are the logical/bitwise operators defined in Visual Basic.


And Operator (Visual Basic)
Not Operator (Visual Basic)
Or Operator (Visual Basic)

Page 2 of 10
Xor Operator (Visual Basic)

Arithmetic Operations
You can add two values in an expression together with the + Operator (Visual Basic), or
subtract one from another with the - Operator (Visual Basic), as the following example
demonstrates.
Dim x As Integer
x = 67 + 34
x = 32 - 12
Negation also uses the - Operator (Visual Basic), but with only one operand, as the
following example demonstrates.
Dim x As Integer = 65
Dim y As Integer
y = -x
Multiplication and division use the * Operator (Visual Basic) and / Operator (Visual
Basic), respectively, as the following example demonstrates.
Dim y As Double
y = 45 * 55.23
y = 32 / 23
Exponentiation uses the ^ Operator (Visual Basic), as the following example
demonstrates.
Dim z As Double
z = 23 ^ 3
' The preceding statement sets z to 12167 (the cube of 23).
Integer division is carried out using the \ Operator. Integer division returns the quotient,
that is, the integer that represents the number of times the divisor can divide into the
dividend without consideration of any remainder.
Dim k As Integer
k = 23 \ 5
' The preceding statement sets k to 4.
Modulus arithmetic is performed using the Mod Operator (Visual Basic). This operator
returns the remainder after dividing the divisor into the dividend an integral number of
times. If both divisor and dividend are integral types, the returned value is integral. If
divisor and dividend are floating-point types, the returned value is also floating-point.
The following example demonstrates this behavior.
Dim x As Integer = 100
Dim y As Integer = 6
Dim z As Integer
z = x Mod y
' The preceding statement sets z to 4.
Dim a As Double = 100.3
Dim b As Double = 4.13

Page 3 of 10
Dim c As Double
c = a Mod b
' The preceding statement sets c to 1.18.
Comparison operators compare two expressions and return a Boolean value that
represents the relationship of their values. There are operators for comparing numeric
values, operators for comparing strings, and operators for comparing objects. All three
types of operators are discussed herein.

Comparing Numeric Values


Visual Basic compares numeric values using six numeric comparison operators. Each
operator takes as operands two expressions that evaluate to numeric values. The
following table lists the operators and shows examples of each.

Operator Condition tested Examples


= (Equality) Is the value of the first 23 = 33 ' False
expression equal to the 23 = 23 ' True
value of the second? 23 = 12 ' False
<> (Inequality) Is the value of the first 23 <> 33 ' True
expression unequal to the 23 <> 23 ' False
value of the second? 23 <> 12 ' True
< (Less than) Is the value of the first 23 < 33 ' True
expression less than the 23 < 23 ' False
value of the second? 23 < 12 ' False
> (Greater than) Is the value of the first 23 > 33 ' False
expression greater than the 23 > 23 ' False
value of the second? 23 > 12 ' True
<= (Less than or equal to) Is the value of the first 23 <= 33 ' True
expression less than or 23 <= 23 ' True
equal to the value of the 23 <= 12 ' False
second?
>= (Greater than or equal to) Is the value of the first 23 >= 33 ' False
expression greater than or 23 >= 23 ' True
equal to the value of the 23 >= 12 ' True
second?

Comparing Strings
The numeric operators allow you to compare String values based on their sort order, as
the following example shows.
"73" < "9"
' The result of the preceding comparison is True.

Page 4 of 10
The result in the preceding example is True because the first character in the first string
sorts before the first character in the second string. If the first characters were equal, the
comparison would continue to the next character in both strings, and so on. You can also
test equality of strings using the equality operator, as the following example shows.
"734" = "734"
' The result of the preceding comparison is True.
If one string is a prefix of another, such as "aa" and "aaa", the longer string is considered
to be greater than the shorter string. The following example illustrates this.
"aaa" > "aa"
' The result of the preceding comparison is True.
The sort order is based on either a binary comparison or a textual comparison depending
on the setting of Option Compare.
Option Compare { Binary | Text }

Concatenate Operation
Concatenation operators join multiple strings into a single string. There are two
concatenation operators, + and &. Both carry out the basic concatenation operation, as the
following example shows.
Dim x As String = "Con" & "caten" & "ation"
Dim y As String = "Con" + "caten" + "ation"
' The preceding statements set both x and y to "Concatenation".
These operators can also concatenate String variables, as the following example shows.
Dim a As String = "abc"
Dim d As String = "def"
Dim z As String = a & d
Dim w As String = a + d
' The preceding statements set both z and w to "abcdef".
Differences Between the Two Concatenation Operators
The + Operator (Visual Basic) has the primary purpose of adding two numbers. However,
it can also concatenate numeric operands with string operands. The + operator has a
complex set of rules that determine whether to add, concatenate, signal a compiler error,
or throw a run-time InvalidCastException exception.
The & Operator (Visual Basic) is defined only for String operands, and it always widens
its operands to String, regardless of the setting of Option Strict. The & operator is
recommended for string concatenation because it is defined exclusively for strings and
reduces your chances of generating an unintended conversion.

Unary Logical Operator

Page 5 of 10
Logical operators compare Boolean expressions and return a Boolean result. The And,
Or, and Xor operators are binary because they take two operands, while the Not operator
is unary because it takes a single operand. Some of these operators can also perform
bitwise logical operations on integral values.

The Not Operator (Visual Basic) performs logical negation on a Boolean expression. It
yields the logical opposite of its operand. If the expression evaluates to True, then Not
returns False; if the expression evaluates to False, then Not returns True. The following
example illustrates this.
Dim x, y As Boolean
x = Not 23 > 14
y = Not 23 > 67
' The preceding statements set x to False and y to True.

Binary Logical Operators


The And Operator (Visual Basic) performs logical conjunction on two Boolean
expressions. If both expressions evaluate to True, then And returns True. If at least one of
the expressions evaluates to False, then And returns False.
The Or Operator (Visual Basic) performs logical disjunction or inclusion on two Boolean
expressions. If either expression evaluates to True, or both evaluate to True, then Or
returns True. If neither expression evaluates to True, Or returns False.
The Xor Operator (Visual Basic) performs logical exclusion on two Boolean expressions.
If exactly one expression evaluates to True, but not both, Xor returns True. If both
expressions evaluate to True or both evaluate to False, Xor returns False.
The following example illustrates the And, Or, and Xor operators.
Dim a, b, c, d, e, f, g As Boolean

a = 23 > 14 And 11 > 8


b = 14 > 23 And 11 > 8
' The preceding statements set a to True and b to False.

c = 23 > 14 Or 8 > 11
d = 23 > 67 Or 8 > 11
' The preceding statements set c to True and d to False.

e = 23 > 67 Xor 11 > 8


f = 23 > 14 Xor 11 > 8
g = 14 > 23 Xor 8 > 11
' The preceding statements set e to True, f to False, and g to False.

Bitwise Operations

Page 6 of 10
Bitwise operations evaluate two integral values in binary (base 2) form. They compare
the bits at corresponding positions and then assign values based on the comparison. The
following example illustrates the And operator.
Dim x As Integer
x = 3 And 5
The preceding example sets the value of x to 1. This happens for the following reasons:
The values are treated as binary:
3 in binary form = 011
5 in binary form = 101
The And operator compares the binary representations, one binary position (bit) at a time.
If both bits at a given position are 1, then a 1 is placed in that position in the result. If
either bit is 0, then a 0 is placed in that position in the result. In the preceding example
this works out as follows:
011 (3 in binary form)
101 (5 in binary form)
001 (The result, in binary form)
The result is treated as decimal. The value 001 is the binary representation of 1, so x = 1.
The bitwise Or operation is similar, except that a 1 is assigned to the result bit if either or
both of the compared bits is 1. Xor assigns a 1 to the result bit if exactly one of the
compared bits (not both) is 1. Not takes a single operand and inverts all the bits, including
the sign bit, and assigns that value to the result. This means that for signed positive
numbers, Not always returns a negative value, and for negative numbers, Not always
returns a positive or zero value.
Note
Bitwise operations can be performed on integral types only. Floating-point values must
be converted to integral types before bitwise operation can proceed.

Assignment statements carry out assignment operations, which consist of taking the value
on the right side of the assignment operator (=) and storing it in the element on the left, as
in the following example.
v = 42
In the preceding example, the assignment statement stores the literal value 42 in the
variable v.

Eligible Programming Elements


The programming element on the left side of the assignment operator must be able to
accept and store a value. This means it must be a variable or property that is not
ReadOnly, or it must be an array element. In the context of an assignment statement, such
an element is sometimes called an lvalue, for "left value."

Page 7 of 10
The value on the right side of the assignment operator is generated by an expression,
which can consist of any combination of literals, constants, variables, properties, array
elements, other expressions, or function calls. The following example illustrates this.
x = y + z + findResult(3)
The preceding example adds the value held in variable y to the value held in variable z,
and then adds the value returned by the call to function findResult. The total value of this
expression is then stored in variable x.

Data Types in Assignment Statements


In addition to numeric values, the assignment operator can also assign String values, as
the following example illustrates.
Dim a, b As String
a = "String variable assignment"
b = "Con" & "cat" & "enation"
' The preceding statement assigns the value "Concatenation" to b.
You can also assign Boolean values, using either a Boolean literal or a Boolean
expression, as the following example illustrates.
Dim r, s, t As Boolean
r = True
s = 45 > 1003
t = 45 > 1003 Or 45 > 17
' The preceding statements assign False to s and True to t.
Similarly, you can assign appropriate values to programming elements of the Char, Date,
or Object data type. You can also assign an object instance to an element declared to be of
the class from which that instance is created.

Compound Assignment Statements


Compound assignment statements first perform an operation on an expression before
assigning it to a programming element. The following example illustrates one of these
operators, +=, which increments the value of the variable on the left side of the operator
by the value of the expression on the right.
n += 1
The preceding example adds 1 to the value of n, and then stores that new value in n. It is
a shorthand equivalent of the following statement:
n=n+1
A variety of compound assignment operations can be performed using operators of this
type. For a list of these operators and more information about them, see Assignment
Operators.
The concatenation assignment operator (&=) is useful for adding a string to the end of
already existing strings, as the following example illustrates.

Page 8 of 10
Dim q As String = "Sample "
q &= "String"
' q now contains "Sample String".

When several operations occur in an expression, each part is evaluated and resolved in a
predetermined order called operator precedence.

Precedence Rules
When expressions contain operators from more than one category, they are evaluated
according to the following rules:
The arithmetic and concatenation operators have the order of precedence
described below, and all have higher precedence than the comparison, logical, and
bitwise operators.
All comparison operators have equal precedence, and all have higher precedence
than the logical and bitwise operators, but lower precedence than the arithmetic
and concatenation operators.
The logical and bitwise operators have the order of precedence described below,
and all have lower precedence than the arithmetic, concatenation, and comparison
operators.
Operators with equal precedence are evaluated left to right in the order in which
they appear in the expression.

Precedence Order
Operators are evaluated in the following order of precedence:
Arithmetic and Concatenation Operators
Exponentiation (^)
Unary identity and negation (+, )
Multiplication and floating-point division (*, /)
Integer division (\)
Modulus arithmetic (Mod)
Addition and subtraction (+, ), string concatenation (+)
String concatenation (&)
Comparison Operators
All comparison operators (=, <>, <, <=, >, >=)
Logical and Bitwise Operators
Negation (Not)

Page 9 of 10
Conjunction (And)
Inclusive disjunction (Or)
Exclusive disjunction (Xor)

The = operator is only the equality comparison operator, not the assignment operator.
The string concatenation operator (&) is not an arithmetic operator, but in precedence it is
grouped with the arithmetic operators.

Associativity
When operators of equal precedence appear together in an expression, for example
multiplication and division, the compiler evaluates each operation as it encounters it from
left to right. The following example illustrates this.
Dim n1 As Integer = 96 / 8 / 4
Dim n2 As Integer = (96 / 8) / 4
Dim n3 As Integer = 96 / (8 / 4)
The first expression evaluates the division 96 / 8 (resulting in 12) and then the division 12
/ 4, resulting in 3. Because the compiler evaluates the operations for n1 from left to right,
the evaluation is exactly the same when that order is explicitly indicated for n2. Both n1
and n2 have a result of 3. By contrast, n3 has a result of 48, because the parentheses force
the compiler to evaluate 8 / 4 first.
Because of this behavior, operators are said to be left associative in Visual Basic.

Page 10 of 10

You might also like