A statement is one logical line (or several joined with a colon). Block statements start with a keyword and end with End plus that keyword, or with their own closer. Local variables are declared with Dim inside any of these blocks (see types and variables).
Conditions and selection
If n > 10 Then
Console.WriteLine("big")
ElseIf n > 5 Then
Console.WriteLine("medium")
Else
Console.WriteLine("small")
End If
If n = 0 Then Console.WriteLine("zero") Else Console.WriteLine("not zero")
Select Case n
Case 1, 2, 3
Console.WriteLine("low")
Case 4 To 9
Console.WriteLine("middle")
Case Is >= 10
Console.WriteLine("high")
Case Else
Console.WriteLine("other")
End Select
If, and Select Case; the code was compiled with the .NET 10 SDK.- If has a block form (
If … Then, any number ofElseIf … Then, oneElse,End If) and a single-line form (If c Then a Else b, where the parts may hold several statements separated by colons). The condition must be Boolean (withOption Strict Offa number is accepted). - Select Case compares one expression with the cases in order and runs the first that matches. A case is a list of values, ranges (
4 To 9), comparisons (Is >= 10) or a mix;Case Elseis the fallback. There is no fall-through, and the cases may be strings, enumerations and any type with the operators needed.
Loops
For i As Integer = 0 To 10 Step 2
If i = 4 Then Continue For
If i > 8 Then Exit For
Console.WriteLine(i)
Next
For Each ch As Char In text
Console.Write(ch)
Next
While k < 3
k += 1
End While
Do While k < 6
k += 1
Loop
Do
k -= 1
Loop Until k < 3
| Statement | Meaning |
|---|---|
For v [As T] = a To b [Step s] … Next [v] | counts from a to b; Step may be negative; the bounds and the step are evaluated once. The variable may be declared in the statement (then it is local to the loop) |
For Each v [As T] In collection … Next | runs once per element of an array or any object with a GetEnumerator (IEnumerable); the collection must not change shape during the loop |
While c … End While | tests first (While … Wend is the VB6 form; Wend is reserved in .NET but the block ends with End While) |
Do [While|Until c] … Loop [While|Until c] | tests at the top or at the bottom (the body then runs at least once); Until is the negation of While |
Exit For, Exit While, Exit Do | leaves the innermost loop of that kind; Continue For|While|Do goes to the next iteration (version 8) |
Exceptions
Try
Using reader As New StreamReader(path)
Console.WriteLine(reader.ReadLine())
End Using
Catch ex As FileNotFoundException When path.Length > 0
Console.WriteLine("missing " & ex.FileName)
Catch ex As IOException
Throw
Catch ex As Exception
Throw New InvalidOperationException("failed", ex)
Finally
Console.WriteLine("done")
End Try
- Try … Catch … Finally … End Try: the first
Catchwhose type matches (and whoseWhenfilter is true) handles the exception;Finallyalways runs.Catchalone catches everything.Exit Tryleaves the block. - Throw throws an exception object;
Throwwith nothing rethrows the current one and keeps its stack. - On Error is the unstructured style from VB6, still allowed in a procedure that has no
Try:On Error GoTo label,On Error GoTo 0(off),On Error GoTo -1(clear),On Error Resume Next;Resume,Resume NextandResume labelcontinue after a handler; theErrobject holds the error (Err.Number,Err.Description,Err.Raise);Errorraises one by number.
Function Old(x As Integer) As Integer
On Error GoTo Handler
Dim r = 10 \ x
Return r
Handler:
If Err.Number = 11 Then Return -1
Resume Next
End Function
Resources, blocks and branches
Dim o As New Object
SyncLock o
Console.WriteLine("locked")
End SyncLock
Dim sb As New System.Text.StringBuilder
With sb
.Append("a")
.Append("b")
End With
Dim i = 0
Again:
i += 1
If i < 3 Then GoTo Again
Dim a(3) As Integer
Erase a
ReDim a(7)
Dim s = "hello"
Mid(s, 1, 1) = "J"
Call Console.WriteLine("called")
Stop
With, a label and GoTo, arrays, Mid assignment, Call and Stop.- Using declares or evaluates a resource and calls its
DisposeatEnd Using, whatever happens (version 8). - SyncLock takes the monitor of an object so only one thread runs the block.
- With evaluates an object once; inside, a name that starts with a dot is a member of it.
- GoTo jumps to a label in the same procedure; a label is a name (or number) followed by a colon at the start of a line. It cannot jump into a block.
GoSubandReturnwithout a value are VB6 forms. - Return leaves a procedure (with the value in a function);
Exit Sub,Exit FunctionandExit Propertydo the same, and a function can also assign to its own name. - ReDim / Erase resize and clear arrays; Stop breaks into a debugger; End ends the program; Call is the optional keyword for a call statement.
- RaiseEvent, AddHandler, RemoveHandler belong to events; Await and Yield to async and iterator methods.
Not described
Known, not yet covered
- Reference: the exact rules of
Forloop control variables (type of the counter, overflow, loop-variable scope and the closure rules),For Eachover arrays of arrays and the enumeration of dictionary entries are summarised, not specified. - Reference: the semantics of
Resumeforms, the ordering ofFinallywithOn Error, and the definite-assignment warnings are in the statements chapter of the specification and are not listed here.
See also
- Operators and expressions – the expressions inside statements
- VB6 and VBA – the file and I/O statements of the older languages