0

Why would you leave the open and close brackets in the code without the condition first? I've seen examples in C# where the code does compile when you have something like this:

{
  Console.WriteLine("Hey");
}

Is this just bad syntax? or something else?

3
  • 2
    It just creates a new scope. In this example there is not really a good use for it. Oct 5, 2022 at 6:36
  • If you were to, for instance, declare a variable within those braces, it would exist only within those braces. Oct 5, 2022 at 6:40
  • You might want to look at the block statement and then realise that this simplifies the c# language grammar significantly because it doesn't then need to enumerate separate cases for single-line vs multi-line if blocks, for example. Oct 5, 2022 at 6:46

1 Answer 1

2

New brackets means new scope. For example if you want to create variable, which should exists only in specific part of code you can surround it with brackets:

{
   var a = 1;
   {
      var b = 2;
      //here 'a' and 'b' exist
   }
   //only 'a' exists
   {
      var b = 2;
      //again 'a' and 'b' exist
   }
   //again only 'a' exists
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.