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

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

    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
    

提交回复
热议问题