Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 766
Chris Sutton Avatar asked Sep 17 '08 16:09

Chris Sutton


2 Answers

Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects.

Ray Hayes points out that the .NET garbage collector will not immediately collect the out-of-scope objects, so scoping is the main benefit.

like image 190
Ed Schwehm Avatar answered Nov 15 '22 21:11

Ed Schwehm


An example would be if you wanted to reuse a variable name, normally you can't reuse variable names This is not valid

        int a = 10;
        Console.WriteLine(a);

        int a = 20;
        Console.WriteLine(a);

but this is:

    {
        int a = 10;
        Console.WriteLine(a);
    }
    {
        int a = 20;
        Console.WriteLine(a);
    }

The only thing I can think of right now, is for example if you were processing some large object, and you extracted some information out of it, and after that you were going to perform a bunch of operations, you could put the large object processing in a block, so that it goes out of scope, then continue with the other operations

    {
        //Process a large object and extract some data
    }
    //large object is out of scope here and will be garbage collected, 
    //you can now perform other operations with the extracted data that can take a long time, 
    //without holding the large object in memory

    //do processing with extracted data
like image 28
BlackTigerX Avatar answered Nov 15 '22 21:11

BlackTigerX