Creating scopes with braces

Creating scopes with braces without any statements

Home DailyDrop

Daily Knowledge Drop

Usually braces {} are uses to define the scope of a specific statement (method, if statement, for loop etc) - but braces can also be used to define a scope without specifying a statement


Example

Below is a simple code snippet to demonstrate the scopes:


// instantiated in the main outer scope
var outerVariable = 1;

// if statement creates its own scope
if(outerVariable == 1)
{
    // instantiated within the scope of the if statement
    var innerVariable = 100;
    Console.WriteLine($"In the if statement, innerVariable: {innerVariable}");
}

// a scope is created with the use of braces and no specific statement
{
    // cannot be declared here, as a variable of the same name is already 
    // declared in the outer scope
    //var outerVariable = 2; NOT allowed

    // instantiated within the scope
    // same name as used above, and allowed
    var innerVariable = 101;
    Console.WriteLine($"In scoped statement, innerVariable: {innerVariable}");
}

// Cannot be accessed, as the visibility of this variable is confined to 
// the scope in which it was created
//inIfVariable = 102; NOT allowed

Console.WriteLine($"In the main scope, outerVariable: {outerVariable}");

Notes

While not encouraging the reusing of variables names in the same scope, if it is required, braces can be used to create smaller scopes. This will limit the visibility of variables so that they can be reused within multiple smaller scopes.
However this should not be abused, as it can make the code harder to read - often it is a better idea to declare a variable to share across all scopes (i.e a method), or convert a smaller scope into its own method.


References

Five C# Features You Might Not Know

Daily Drop 51: 13-04-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net dictionary concurrentdictionary