Anonymous block in C#

Viewed 403

I am trying to understand below code - What is the use of below anonymous block

{
    Console.WriteLine("Hello World2");
}

Above code is available inside a method - I am new to c# and trying to understand it .

1 Answers

Use in this example: none.

Use of an anonymous block: acts just like any block, with its own scope.

eg, this code will not compile as a is not in scope outside the block:

{
    var a = 2;
    Console.WriteLine(a);
}
Console.WriteLine(a);

You can read more info here, although that is geared slightly to c/c++ but mostly holds true in c#. A more existential discussion is also available here.

Related