Why can't we define a variable inside an if statement?

前端 未结 5 1058
余生分开走
余生分开走 2020-12-01 04:13

Maybe this question has been answered before, but the word if occurs so often it\'s hard to find it.

The example doesn\'t make sense (the expression is

5条回答
  •  無奈伤痛
    2020-12-01 04:43

    This is because section 8.5.1 of the C# language spec. states:

    Furthermore, a variable initializer in a local variable declaration corresponds exactly to an assignment statement that is inserted immediately after the declaration.

    This basically means that, when you do:

    StringBuilder sb = new StringBuilder("test")
    

    You're, in effect, doing the exact same thing as:

    StringBuilder sb; sb = new StringBuilder("test")
    

    As such, there is no longer a return value for your check against != null, as the assignment isn't a single expression, but rather a statement, which is a local-variable-declarator comprised of an identifier followed by an expression.

    The language specification gives this example, stating that this:

    void F() {
       int x = 1, y, z = x * 2;
    }
    

    Is exactly equivalent to:

    void F() {
       int x; x = 1;
       int y;
       int z; z = x * 2;
    }
    

提交回复
热议问题