Chuyển đến nội dung

Bài 6 · Syntax and Types

Operators and Expressions

Learn every operator in Visual Basic .NET: arithmetic, assignment, comparison, logical and bitwise operators, the string operators & and Like, precedence, short-circuiting and If() expressions.

An expression is anything that produces a value: 2 + 3, price * quantity, name.Length > 3. Operators combine values into expressions. VB.NET has a rich, readable operator set, with a few twists that differ from C-style languages: = compares, <> means "not equal", & joins strings, and logical operators come in short-circuit and non-short-circuit versions. Listings here are VB.NET (read-only); runnable C# stand-ins test the same ideas.

Arithmetic operators

Operator Meaning Example Result
+ Addition 7 + 2 9
- Subtraction 7 - 2 5
* Multiplication 7 * 2 14
/ Division (floating point) 7 / 2 3.5
\ Integer division 7 \ 2 3
Mod Remainder 7 Mod 2 1
^ Exponent (always Double) 2 ^ 10 1024

^ returns a Double, so Dim p As Integer = 2 ^ 10 needs a conversion when Option Strict On (see Option Strict and Conversions). Negative numbers: -7 \ 2 is -3 (it truncates toward zero) and -7 Mod 2 is -1.

Assignment and compound assignment

= assigns. Compound operators combine an operation with assignment:

VB
Dim n As Integer = 10
n += 5      ' 15
n -= 3      ' 12
n *= 2      ' 24
n \= 5      ' 4
n ^= 2      ' 16  (n = n ^ 2, converts back to Integer)
Dim s As String = "ab"
s &= "cd"   ' "abcd"

VB has no ++ or --; write n += 1.

Comparison operators

=, <>, <, >, <=, >= all return a Boolean. The same = symbol is used for assignment and equality: the compiler decides from context (If x = 5 Then compares, x = 5 on its own line assigns).

For objects, Is and IsNot compare references:

VB
Dim a As New List(Of Integer)
Dim b = a
Console.WriteLine(a Is b)           ' True
Console.WriteLine(a Is Nothing)     ' False
Console.WriteLine(a IsNot Nothing)  ' True

Never write x = Nothing to test for null; use x Is Nothing.

Logical operators and short-circuiting

Operator Evaluates right side? Use
And always bitwise and non-short-circuit logical AND
Or always bitwise and non-short-circuit logical OR
AndAlso only if left is True normal logical AND
OrElse only if left is False normal logical OR
Not n/a negation
Xor always exclusive OR

Use AndAlso/OrElse for conditions. They prevent errors such as:

VB
If text IsNot Nothing AndAlso text.Length > 3 Then
    Console.WriteLine("long text")
End If

With plain And, text.Length would still run when text is Nothing and crash.

C# Stand-in (C#): short-circuit versus non-short-circuit

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Bitwise operators and shifts

And, Or, Xor and Not also work on integers bit by bit. << and >> shift bits:

VB
Dim flags As Integer = 0b0101      ' binary literal, 5
Console.WriteLine(flags And 0b0100)   ' 4
Console.WriteLine(flags Or 0b0010)    ' 7
Console.WriteLine(flags Xor 0b0001)   ' 4
Console.WriteLine(1 << 4)             ' 16

Bitwise logic is what Enum flag sets use; see Structures, Enums and Generics.

C# Stand-in (C#): bit operations

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

String operators

& concatenates and converts both sides to strings. + also works on two strings but can try to add numbers if a side is numeric, so prefer &.

Like does simple pattern matching with wildcards: ? one character, * any run, # one digit, [abc] a set, [!abc] not in set.

VB
Console.WriteLine("report-2025" Like "report-####")   ' True
Console.WriteLine("Bob" Like "B?b")                   ' True
Console.WriteLine("abc" Like "[a-c]*")                ' True

Precedence

When an expression has several operators, VB applies them in this order (highest first):

  1. ^
  2. unary -, +
  3. *, /
  4. \
  5. Mod
  6. +, -
  7. &
  8. <<, >>
  9. comparison (=, <>, <, >, <=, >=, Like, Is, IsNot)
  10. Not
  11. And, AndAlso
  12. Or, OrElse, Xor

Two consequences: -2 ^ 2 is -4 in VB (the exponent binds tighter than the unary minus, so it is -(2 ^ 2)), and "a" & 1 + 2 yields "a3" because + binds before &. When in doubt, use parentheses; they cost nothing and make intent obvious.

The If() operator

If(condition, whenTrue, whenFalse) is a conditional expression, and If(value, fallback) supplies a default when a reference is Nothing:

VB
Dim age As Integer = 20
Dim label As String = If(age >= 18, "adult", "minor")

Dim nickname As String = Nothing
Dim shown As String = If(nickname, "(none)")   ' "(none)"

Both branches are evaluated lazily, only the chosen one runs. Do not confuse it with the old IIf function, which evaluates both arguments.

C# Stand-in (C#): conditional and null-coalescing expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which operator should you normally use for the logical AND in an If condition?

    AndAlso short-circuits, so the right side is skipped when the left is False. VB has no && operator.
  2. 2. What does 17 Mod 5 return?

    Mod returns the remainder: 17 = 3 * 5 + 2.
  3. 3. How do you test whether an object reference is null?

    Is and IsNot compare references; they are the correct way to test for Nothing.
  4. 4. What is the result of If(Nothing, "x") when the first argument is a String variable holding Nothing?

    The two-argument If returns the first value when it is not Nothing; otherwise it returns the second.
  5. 5. Which operator does VB.NET NOT have?

    VB.NET has no increment operator; write n += 1.

Summary

  • Arithmetic: + - * / \ Mod ^; / is floating point, \ is integer division; compound forms like += and &= exist, but no ++.
  • = both assigns and compares; <> is not-equal; Is/IsNot compare references.
  • Prefer AndAlso and OrElse; plain And/Or evaluate both sides and also work bitwise.
  • & joins strings, Like matches simple patterns.
  • Use parentheses to avoid precedence surprises; If(a, b, c) and If(x, default) are the conditional operators.

Next: Strings and Text

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.