Possible Duplicate:
When do you use code blocks?
Ok, this might be a stupid question and I might be missing something obvious but as I slowly learn C# this has kept nagging me for a while now.
The following code obviously compiles just fine:
public void Foo()
{
{
int i = 1;
i++;
}
{
int i = 1;
i--;
}
}
I understand that {} blocks can be used for scoping. The question is why would you want to do this? What problems does this feature solve?
There is no harm that I can see in using them barring that it does add to a more confusing code as these kind of scopes can be more easily overlooked compared those “tied” to flow controls, iterations, etc.
It is useful in
switchstatements where your variable declarations can become confusing:Confusing code:
Clear code: