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.
Block scoping ensures that any variables defined within those braces don't become global variables. They instead have local scope. Having this type of control over how variables are scoped helps you prevent unexpected behaviour in your code.
Function scoped variables: A function scoped variable means that the variable defined within a function will not accessible from outside the function. Block scoped variables: A block scoped variable means that the variable defined within a block will not be accessible from outside the block.
a scope is where you can refer to a variable. a block defines a block scope a variable defined inside a block will be defined only inside that block and you can't reference it after the end of block.
Block Scope: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop. To be consise the variables declared inside the curly braces are called as within block scope.
It is useful in switch
statements where your variable declarations can become confusing:
Confusing code:
switch (true)
{
case true:
var msg = "This is true.";
var copy = msg;
break;
case false:
msg = "This is false.";
copy = msg;
break;
}
Clear code:
switch (true)
{
case true:
{
var msg = "This is true.";
var copy = msg;
break;
}
case false:
{
var msg = "This is false.";
var copy = msg;
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With