c# – Compiler use of curly braces

Question:

Any if can be written with or without curly braces. For example:

bool j = true;
if(j==true)
    MessageBox.Show("That's true")

Or like this:

bool j = true;
if(j==true)
{
   MessageBox.Show("That's true")
}

The conversation is only about if constructions with a single action. Hence a few questions:

  1. Does the compiler ignore these brackets?
  2. If not, does the program pay attention to them?
  3. Do these parentheses affect the performance of the program (even if it is very insignificant)?

Answer:

Referring to the specification

For if statement

if_statement:
    | 'if' '(' boolean_expression ')' embedded_statement
    | 'if' '(' boolean_expression ')' embedded_statement 'else' embedded_statement
    ;

For cycles. for example while:

while_statement:
    | 'while' '(' boolean_expression ')' embedded_statement
    ;

As you can see, there are no brackets at the specification level.

In turn, embedded_statement expands like this:

embedded_statement:
    | block
    | empty_statement
    | expression_statement
    | selection_statement
    | iteration_statement
    | jump_statement
    | try_statement
    | checked_statement
    | unchecked_statement
    | lock_statement
    | using_statement
    | yield_statement
    | embedded_statement_unsafe
    ;

And the brackets in this case are part of the block

block:
    | '{' statement_list? '}'
    ;

Thus, we can say that:

  1. The compiler does not ignore brackets, as they are part of the syntax
  2. the program itself cannot pay attention to them, but there is still a difference in use. For example: variables can be defined inside a block, without brackets – no.
  3. Since this is a purely syntactic construction, the brackets have no effect on performance.
Scroll to Top