Operators and Comparisons
Prerequisites: Numbers and math
Comparison operators
Module Program
Sub Main()
Console.WriteLine(5 = 5)
Console.WriteLine(5 <> 3)
Console.WriteLine(5 > 3)
Console.WriteLine(5 <= 3)
End Sub
End Module
True
True
True
False
= means comparison inside an expression and assignment in a
statement like x = 5. "Not equal" is <>.
Logical operators
Module Program
Function Check(label As String, result As Boolean) As Boolean
Console.WriteLine($" checking {label}")
Return result
End Function
Sub Main()
Console.WriteLine("And:")
Console.WriteLine(Check("a", False) And Check("b", True))
Console.WriteLine("AndAlso:")
Console.WriteLine(Check("a", False) AndAlso Check("b", True))
Console.WriteLine("OrElse:")
Console.WriteLine(Check("a", True) OrElse Check("b", True))
Console.WriteLine(Not True)
Console.WriteLine(True Xor True)
End Sub
End Module
And:
checking a
checking b
False
AndAlso:
checking a
False
OrElse:
checking a
True
False
False
AndAlsoandOrElseshort-circuit: the right side is skipped when the left side already decides the answer. Use them in conditions.And,Or, andXoralways evaluate both sides; on integers they are bitwise operators (6 And 3is2).
Short-circuiting protects you from errors:
Module Program
Sub Main()
Dim name As String = Nothing
If name IsNot Nothing AndAlso name.Length > 3 Then
Console.WriteLine("long name")
Else
Console.WriteLine("no name or short name")
End If
End Sub
End Module
no name or short name
With And, name.Length would run even though name is Nothing, and
throw a NullReferenceException.
Is, IsNot, TypeOf, and Like
Module Program
Sub Main()
Dim a As Object = "text"
Dim b As Object = Nothing
Console.WriteLine(b Is Nothing)
Console.WriteLine(a IsNot Nothing)
Console.WriteLine(TypeOf a Is String)
Console.WriteLine("report2025.txt" Like "report####.txt")
Console.WriteLine("Visual Basic" Like "V*c")
End Sub
End Module
True
True
True
True
True
Is compares references (is it the same object, or Nothing?).
Like does simple wildcard matching: * any text, ? one character,
# one digit.
The If operator
If(condition, a, b) returns a or b — VB's conditional expression.
If(value, fallback) returns fallback when value is Nothing:
Module Program
Sub Main()
Dim age = 20
Console.WriteLine(If(age >= 18, "adult", "minor"))
Dim nickname As String = Nothing
Console.WriteLine(If(nickname, "(no nickname)"))
End Sub
End Module
adult
(no nickname)
Operator precedence
From highest to lowest: ^, unary -, * /, \, Mod, + -,
&, comparisons, Not, And/AndAlso, Or/OrElse, Xor. When in
doubt, add parentheses.