
Curly brackets may be omitted. In the C# programming language, it is acceptable to omit the curly brackets { } around a one-statement block. This means you can use a simpler syntax for if-statements, foreach-loops or other constructs. However, omitting curly brackets can introduce errors into programs, making them harder to understand.
This C# article explores the curly bracket syntax. It shows why omitting curly brackets is problematic.
First, this example program shows one possible error that can happen when the curly brackets are omitted in a foreach-loop. In the method Bad(), a programmer assumed that the two Console.WriteLine statements would be executed for every iteration. Instead, the second WriteLine call is only executed once. The second Console.WriteLine should not be indented.
Program that demonstrates curly brackets [C#]
using System;
class Program
{
static int[] _array = { 1, 2 };
static void Main()
{
Bad();
Console.WriteLine();
Good();
}
static void Bad()
{
foreach (int element in _array)
Console.WriteLine(element);
Console.WriteLine(true);
}
static void Good()
{
foreach (int element in _array)
{
Console.WriteLine(element);
Console.WriteLine(true);
}
}
}
Output
1
2
True
1
True
2
TrueSecond method. In the Good() method, though, a smart programmer used the curly brackets { } around the two-statement block of the foreach-loop. When this method is compiled and executed, it will print both values on every iteration through the loop as desired.

Visual Studio actually provides a lot of help in this case. It does not report a warning or an error on the example program, but if you force the program to reformat its indentation, as by replacing the } bracket at the end, it will reindent all the statements. Then, the problematic WriteLine call will be separated from the loop body, improving clarity.

It is important to use curly brackets in your C# programs whenever you have more than one statement in a block. This applies to selection statements such as the if-statement and also looping constructs. To our advantage, though, Visual Studio provides helpful indentation fixes when necessary.
Visual Studio Tips