Variable declarations following if statements

The C# language specification distinguishes between three types of statements (see chapter 8 for more details). In general you can have these statements:

  • labeled-statement – my guess that this is for the old-fashioned goto statement
  • declaration-statement – which would be a variable declaration
  • embedded-statement – which includes pretty much all the remaining statements

In the if statement the body has to be embedded-statement, which explains why the first version of the code doesn’t work. Here is the syntax of if from the specification (section 8.7.1):

if ( boolean-expression ) embedded-statement
if ( boolean-expression ) embedded-statement else embedded-statement

A variable declaration is declaration-statement, so it cannot appear in the body. If you enclose the declaration in brackets, you’ll get a statement block, which is an embedded-statement (and so it can appear in that position).

Leave a Comment