3

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 .

ColinM
  • 2,622
  • 17
  • 29
Codified
  • 135
  • 9
  • If some code is wrapped in anonymous blocks, its scope is limited by the brackets of the block. – AEB Mar 13 '20 at 11:57

1 Answers1

13

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.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 4
    Note that in C# 8 there is a new point to anonymous blocks: When the scope ends, any disposables introduced within the scope via a [`using declaration`](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations) will be disposed at the end of the scope. – Matthew Watson Mar 13 '20 at 11:58
  • 1
    Really good point @MatthewWatson but I wonder if you're going to use them like that why you wouldnt just use the older `using(var x = new DisposibleThing()){ ... }` method of introducing a block. – Jamiec Mar 13 '20 at 12:03
  • @Jamiec Lack of knowledge. Most of the times I see (especially on SO) newbies use odd constructions, it's because they don't know any better. I may be guilty of this, too. Or have been. That's not necessarily the person's fault. Just last week I saw a teacher make the students use out-of-the-world code without any justification. – Fildor Mar 13 '20 at 12:10
  • Yes, I would always use an explict "using" block in those cases, but I thought it worth pointing out. – Matthew Watson Mar 13 '20 at 12:18