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

后端 未结 10 1603
谎友^
谎友^ 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:51

    The one practical reason for it to exist is if you want to restrict the scope of some variable when there is no compelling need to introduce any other reason for the block. In actual practice, this is virtually never useful.

    Personally, my guess is that from a language/compiler point of view it's easier to say that you can put a block anywhere a statement is expected, and they simply didn't go out of their way to prevent you from using it without an if/for/method declaration/ etc.

    Consider the beginning this recent blog post from Eric Lippert. An if statement isn't followed by either a single statement or a number of statements enclosed on curly braces, it's simply followed by a single statement. Anytime you enclose 0 to N statements in curly braces you make that section of code equivalent (from the point of view of the language parser) one statement. This same practice applies to all looping structures as well, although as the main point of the blog post explains, it doesn't apply to try/catch/finally blocks.

    When addressing blocks from that point of view the question then becomes, "Is there a compelling reason to prevent blocks from being used anywhere a single statement could be used?" and the answer is, "No".

提交回复
热议问题