Variable declarations following if statements

后端 未结 4 594
甜味超标
甜味超标 2020-11-28 11:29

An issue came up on another forum and I knew how to fix it, but it revealed a feature of the compiler peculiar to me. The person was getting the error \"Embedded statement c

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 12:28

    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).

提交回复
热议问题