Why does C# allow {} code blocks without a preceding statement?

后端 未结 9 2209
半阙折子戏
半阙折子戏 2020-12-14 13:48

Why does C# allow code blocks without a preceding statement (e.g. if, else, for, while)?

void Main()
{
           


        
9条回答
  •  旧巷少年郎
    2020-12-14 14:27

    I consider {} as a statement that can contain several statements.

    Consider an if statement that exists out of a boolean expression followed by one statement. This would work:

    if (true) Console.Write("FooBar");
    

    This would work as well:

    if (true)
    {
      Console.Write("Foo");
      Console.Write("Bar");
    }
    

    If I'm not mistaken this is called a block statement.

    Since {} can contain other statements it can also contain other {}. The scope of a variable is defined by it's parent {} (block statement).

    The point that I'm trying to make is that {} is just a statement, so it doesn't require an if or whatever...

提交回复
热议问题