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

前端 未结 5 1059
余生分开走
余生分开走 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:49

    Instead of:

    if ((StringBuilder sb = new StringBuilder("test")) != null) {
        Console.WriteLine(sb);
    }
    

    One could also write:

    for (StringBuilder sb = new StringBuilder("test"); sb != null; sb = null) {
        Console.WriteLine(sb);
    }
    

    This for loop will execute once if your variable it not null. At the end of the loop, your temporary variable is set to null. The loop condition then evaluates to false, and the next statement continues after the closing brace is executed. Exactly as your if statement originally intended.

提交回复
热议问题