Begin/End Block Statements
end statement is a block statement that does not perform any logic or functionality in itself, but is used to group two or more statements together so that they can be treated as a single statement – usually in a context where a single statement is expected.
For example, the
then statement expects a single sub-statement after the
then keyword, which will be executed if the condition preceding it evaluates to true. Using a
end pair, a whole block of statements can be tied to the condition instead. Technically speaking, the
end is not part of the
then statement's syntax:
if x ≥ 0 then DoSomething; // if expects only a single sub-statement... if x ≥ 0 then begin // ...but a begin/end statement can be used for that single DoSomething; // statement, allowing to conditionally execute a whole list DoSomethingElse; end;
elsestatements, as well as their
- Infinite loops with the
- Individual clauses in a
- Lambda expressions
By contrast, the following block statements already enclose a list of statements they act upon and do not require an explicit
end pair to act upon multiple statements at once:
Statements vs. Expressions
Like all statements,
end blocks can only be used in a context where a plain statement is expected. They can not act as expressions, because they only represent a bunch of statements to be executed, but not a resulting value. Conversely,
end blocks can not be used in the following constructs:
- As condition for
- As loop expressions in
- As expression for
Async Expressions and
async expressions are special in that they are expressions, but can take either an expression or a plain statement to be run asynchronously. When applied to a statement (as would be the case when using
async keyword results in an expression of a type-less Future, also referred to as a Void Future.
You can read more about
async expressions here.
end Block Statements
end blocks introduce no behavior or logic of their own, they can of course be also used to group one or more (technically, zero or more) statements at any place in code where a statement is allowed, even when not used in the context where the grouping is necessary to pull the statements together.
The following code snippet shows three statements, the second of which is a
end block that itself contains two statements. This is valid, even though the
end pair has no effect, and the code would perform the exact same action without it.
Console.Write('hello'); begin Console.Write(' to'); Console.Write(' the'); end; Console.WriteLine(' world')