What is the value of an anonymous unattached block in C#?

后端 未结 10 1526
谎友^
谎友^ 2021-01-11 20:43

In C# you can make a block inside of a method that is not attached to any other statement.

    public void TestMethod()
    {
        {
            string x          


        
10条回答
  •  终归单人心
    2021-01-11 20:55

    It's a by-product of a the parser rule that statement is either a simple statement or a block. i.e. a block can be used wherever a single statement can.

    e.g.

    if (someCondition)
     SimpleStatement();
    
    if (SomeCondition)
    {
       BlockOfStatements();
    }
    

    Others have pointed out that variable declarations are in scope until the end of the containing block. It's good for temporary vars to have a short scope, but I've never had to use a block on it's own to limit the scope of a variable. Sometimes you use a block underneath a "using" statement for that.

    So generally it's not valuable.

提交回复
热议问题