In the previous if statement examples, only one statement follows if and else: a single System.Console.WriteLine(), similar to Listing 4.24.
With curly braces, however, we can combine statements into a single statement called a block statement or code block, allowing the grouping of multiple statements into a single statement that is the consequence. Take, for example, the highlighted code block in the radius calculation in Listing 4.25 with Output 4.14.
In this example, the if statement checks whether the radius is positive. If so, the area of the circle is calculated and displayed; otherwise, an invalid radius message is displayed.
Notice that in this example, two statements follow the first if. However, these two statements appear within curly braces. The curly braces combine the statements into a code block, which is itself a single statement.
If you omit the curly braces that create a code block in Listing 4.25, only the statement immediately following the Boolean expression executes conditionally. Subsequent statements will execute regardless of the if statement’s Boolean expression. The invalid code is shown in Listing 4.26.
In C#, indentation is used solely to enhance the code readability. The compiler ignores it, so Listing 4.26 is semantically equivalent to Listing 4.27.
Programmers should take great care to avoid subtle bugs such as this, perhaps even going so far as to always include a code block after a control flow statement, even if there is only one statement. A widely accepted coding guideline is to avoid omitting braces, except possibly for the simplest of single-line if statements.
Although unusual, it is possible to have a code block that is not lexically a direct part of a control flow statement. In other words, placing curly braces on their own (e.g., without a conditional or loop) is legal syntax.
In Listing 4.26 and Listing 4.27, the value of pi was represented by the PI constant in the System.Math class. Instead of hardcoding values for π and e (the base of natural logarithms), code should use System.Math.PI and System.Math.E.