Statement Blocks

Blocks provide a way to combine multiple statements and treat them as if they were just one statement, as the language may expect in some places. At the same time, blocks establish a scope for local variables. (See Chapter 4, “Language Essentials,” for more information.) An example of a typical use for blocks is found in various other statements, like the if statement:

if (condition)    statement-if-trueelse    statement-if-false

Notice that the if statement by itself doesn’t prescribe the use of curly braces for its embedded statements. With blocks, we can provide multiple statements in those places:

if (user.Age >= 18){    session.User = user;    NavigateToHomepage(user.Homepage);}else{    LogInvalidAccessAttempt(); ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.