Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of scoping blocks? [duplicate]

Tags:

c#

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.

like image 723
InBetween Avatar asked Jan 11 '12 17:01

InBetween


People also ask

What is an advantage of declaring a variable with block scoping?

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.

What is the difference between scoped and block scoped?

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.

What is the difference between scope and 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.

What is block scoping?

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.


1 Answers

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;
    }
}
like image 178
Devin Burke Avatar answered Nov 03 '22 00:11

Devin Burke