Alex Rivera | Logout

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

Asked 2008-09-17T16:54:04.723
11

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

    public void TestMethod()
    {
        {
            string x = "test";
            string y = x;

            {
                int z = 42;
                int zz = z;
            }
        }
    }

This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block.

Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings.

c#
Edit
Report

1 Answer

0

There is no value to this other than semantic and for scope and garbage collection, none of which is significant in this limited example. If you think it makes the code clearer, for yourself and/or others, then you certainly could use it. However, the more accepted convention for semantic clarification in code generally would use line breaks only with option in-line comments:

public void TestMethod()
{
    //do something with some strings
    string x = "test";
    string y = x;

    //do something else with some ints
    int z = 42;
    int zz = z;
}
answered 2008-09-17T17:07:49.777

Your Answer