 • Print
This chapter is from the book

## Code Blocks ({})

In the previous if statement examples, only one statement follows if and else: a single System.Console.WriteLine(), similar to Listing 3.23.

#### Listing 3.23. if Statement with No Code Block

````if`(input < 9)
`System.Console.WriteLine("Exiting");`
```

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 3.24.

#### Listing 3.24. if Statement Followed by a Code Block

````class` CircleAreaCalculator
{
`static void` Main()
{
`double` radius;  // Declare a variable to store the radius.
`double` area;    // Declare a variable to store the area.

System.Console.Write(`"Enter the radius of the circle: "`);

radius = `double`.Parse(System.Console.ReadLine());

`if`(radius>=0)
`      {                                                                                          `
`          // Calculate the area of the circle.                                                   `
`          area = 3.14*radius*radius;                                                             `
`          System.Console.WriteLine(                                                              `
`              "The area of the circle is: {0}", area);                                           `
`      }                                                                                          `
`else`
{
System.Console.WriteLine(
`"{0} is not a valid radius."`, radius);
}
}
}
```

Output 3.14 shows the results of Listing 3.24.

Output 3.14.

```Enter the radius of the circle: 3
The area of the circle is: 28.26```

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 3.24, 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 3.25.

#### Listing 3.25. Relying on Indentation, Resulting in Invalid Code

````if`(radius>=0)
System.Console.WriteLine(
`"The area of the circle is: {0}"`, area);
```

In C#, indentation is for code readability only. The compiler ignores it, and therefore, the previous code is semantically equivalent to Listing 3.26.

#### Listing 3.26. Semantically Equivalent to Listing 3.25

````if`(radius>=0)
{
`"The area of the circle is: {0}"`, area);