-1

Today, I just happened to accidently add blank curly braces just out in the open that seem to work with the language, to create a sort of a nested scope region that doesn't pertain to do anything other than nest things,

public void Example()
{
    int b = 3;

    //curly braces just floating in the open -- allowed by compiler
    {
        int c = 2;
    }

    //error
    b = c;
}

Is my hypothesis correct that its just a way to explicitly nest things in their own scope?

IbLCYOq
  • 15
  • 2
  • 4
    Yes: it's a block statement that creates a new scope. Effectively, it's the same block statement that you use in `if(cond) { }` – zerkms Dec 01 '20 at 03:41
  • https://stackoverflow.com/questions/3189366/is-it-wrong-to-use-braces-for-variable-scope-purposes – TheGeneral Dec 01 '20 at 03:58

1 Answers1

2

Curly braces create local scope. Consider this code:

        int b = 3;

        {
            int c = 2;
            Console.WriteLine("First Scope:");
            Console.WriteLine(c); //will print 2
        }

        {
            int c = 3;
            Console.WriteLine("Second Scope:");
            Console.WriteLine(c); //will print 3
        }

        //error
        b = c;
  • The c variable in the second curly braces will create a new variable instance
  • The c variable in the first and the second curly braces has no relation
  • variable c assignment outside the curly braces will not be reached and will create syntax error

Similar post: https://social.microsoft.com/Forums/Windows/es-ES/6ce386f2-f27d-42cd-b031-8664b92f8cae/c-curly-braces-without-head?forum=csharpgeneral

Wildan Muhlis
  • 1,553
  • 2
  • 22
  • 43