Why does C# allow code blocks without a preceding statement (e.g. if
, else
, for
, while
)?
void Main()
{
{ // any sense in this?
Console.Write("foo");
}
}
In the context you give, there is no significance. Writing a constant string to the console is going to work the same way anywhere in program flow.1
Instead, you typically use them to restrict the scope of some local variables. This is further elaborated here and here. Look at João Angelo’s answer and Chris Wallis’s answer for brief examples. I believe the same applies to some other languages with C-style syntax as well, not that they’d be relevant to this question though.
1 Unless, of course, you decide to try to be funny and create your own Console
class, with a Write()
method that does something entirely unexpected.