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

后端 未结 9 2216
半阙折子戏
半阙折子戏 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:21

    It is not so much a feature of C# than it is a logical side-effect of many C syntax languages that use braces to define scope.

    In your example the braces have no effect at all, but in the following code they define the scope, and therefore the visibility, of a variable:

    This is allowed as i falls out of scope in the first block and is defined again in the next:

    {
        {
            int i = 0;
        }
    
        {
            int i = 0;
        }
    }
    

    This is not allowed as i has fallen out of scope and is no longer visible in the outer scope:

    {
        {
            int i = 0;
        }
    
        i = 1;
    }
    

    And so on and so on.

提交回复
热议问题