C# if-else statement: Curly braces or not? An in-depth analysis

Introduction

In this article we will see the use of if-else statement with or without curly braces to see what difference does it make in programming practice. We will dive more deep into why using curly braces is recommended. The example is made of C# use under Console Application. Often we see that one-line if statement and same of the one-line statement is written in curly braces. This some time confused beginner who might just started learning programming. This sample illustrates a way to let user to know what difference does it make in their day to day coding practice.

What is if-else statement?

An if statement is used for decision making. It decides the execution of next statement or next "code block" is to be executed if the condition is true. An if condition can also have an else condition which only executes when the condition given in if statement does not satisfies and evaluates into false. If there is no else statement code execution will move forward to the following code line.

Syntax

if(condition)
{
   //statement(s) will execute if the condition is true
}
else
{
   //statement(s) will execute if the condition is false
}

Use of Curly Braces {}:

Curly braces is used to group a set of statement and deceleration. We use them along with loops and conditional statements in order to avoid confusion and to define a clear scope. And it follows a rule every opening brace must have a closing brace in order to define a clear boundary.

One-line statement

Well if there is only one statement to execute after if condition then using curly braces or not doesn't make it different. Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces. Because if the user (or someone else) ever expands the statement it will be required.

Code

This code shows uses without curly braces

if (true)
   Console.WriteLine("Condition match!");
else
   Console.WriteLine("Condition not match!");

Output

Code

Now we see the same above code with curly braces.

if (true)
{
    Console.WriteLine("Condition match!");
}                
else
{
    Console.WriteLine("Condition not match!");
}
Console.ReadLine();

Output

And there is no changes in the output. We are also getting the same output.

One liner statement

In one linear statement we can write if condition like this

if(condition) something();

Let's see an example where the line "Output based on if-condition" is putted on the same line. As the if condition is false this line will not execute and move to the next line "Line separate from if-condition" and it will print on the screen.

static void  Main(string[] args)
{
   if (false) Console.WriteLine("Output based on if-condition");
   Console.WriteLine("Line separate from if-condition");
 
   Console.ReadLine();
}

Some could use the above approach but what mistakes could happened in this approach. Let's say you have a code block like this:

if(condition) //something();
   separateFromIf();

Where separateFromIf() is not part of the If() condition. Now you put a comment on something() and thinking that, compiler would not consider separateFromIf(); is part of the if() condition and would execute independently. But here separateFromIf() would get consider as part of if() condition and will execute depending on whether if() is true or false, which is wrong. As not using curly braces anyone can easily mistake the scope in this scenario.

Let's see this in an example. Suppose in a scenario we are debugging our code and comment out the line "Output based on if-condition" then what will happen. Well if() will consider next following line is part of its scope which is wrong and starting to give wrong output. As it is considering "Line separate from if-condition" as part of its scope and our if condition is false so we are not getting any output. So here compiler is taking wrong decision not having a curly bracket to specify the scope.

static void  Main(string[] args)
{
    if (false) //Console.WriteLine("Output based on if-condition");
    Console.WriteLine("Line separate from if-condition");
 
    Console.ReadLine();
}

Multi-line Statement

With curly braces

Now consider we have an if condition when true multiple statements will get executed. If we use curly braces all statement within curly braces will get executed when "if" condition satisfies.

Code

if (true)
{
   Console.WriteLine("Executed Line 01 inside if-condition <- With curly braces");
   Console.WriteLine("Executed Line 02 inside if-condition <- With curly braces");
   Console.WriteLine("Executed Line 03 inside if-condition <- With curly braces");
}
Console.ReadLine();

Output

When false no statement will get executed.

Code

if (false)
{
    Console.WriteLine("Executed Line 01 inside if-condition <- No curly braces");
    Console.WriteLine("Executed Line 02 inside if-condition <- No curly braces");
    Console.WriteLine("Executed Line 03 inside if-condition <- No curly braces");
}
Console.WriteLine("No output from if-block.");
Console.ReadLine();

Output

Let's see the below example to understand it more clearly. What we are doing here is that checking whether the value assigned in variable is equals 1, if so then increment the value assigned in variable "b" by 1 and replace the value of "c" with new value.

using System;
 
namespace IfCondition
{
    class Program
    {
        static void  Main(string[] args)
        {
            int a = 1, b = 2, c = 3;            
 
            if (a == 1) //Statement true, execute following lines
            {
                b = b + 1;
                c = 5;
            }
             
            Console.WriteLine("Value of b: " + b.ToString());
            Console.WriteLine("Value of c: " + c.ToString());
             
            Console.ReadLine();
        }
    }
}

Here we getting output according to the code flow which is correct, where variable "b" is incrementing by 1 and turning into 3 and "c"'s valu is replaced by 5.

Without curly braces

Now if there is multiple statement without curly braces then statement only after the "if" condition get affected and rest of the statement will get executed separately but will be look like they are executing as part of if() condition, thinking of which is wrong, because following code line after "if" condition should execute only if it is true.

Code

if (true)
Console.WriteLine("Executed Line 01 inside if-condition <- No curly braces");
Console.WriteLine("Executed Line 02 inside if-condition <- No curly braces");
Console.WriteLine("Executed Line 03 inside if-condition <- No curly braces");
Console.ReadLine();

The output might look like this oh! look all the statements under if condition executing but in real case it is not true. What the above code is doing line following by the if condition is executing based on whether it is true or not and rest of the line executing independently. If we look into the following example we can see that actually what happened in the code, which is wrong.

Let's consider the following where "Executed Line 01 inside if-condition <- No curly braces" is not executing as our if() is false.

if (false)
Console.WriteLine("Executed Line 01 inside if-condition <- No curly braces");
Console.WriteLine("Executed Line 02 inside if-condition <- No curly braces");
Console.WriteLine("Executed Line 03 inside if-condition <- No curly braces");
Console.ReadLine();

So above output makes it clear that if there is multiple statement only line immediate after if() is in scope and rest will execute independently.

Now consider a scenario where we have a single statement after if and rest of the code will execute independently

if(false)
//Console.WriteLine("Executed Line 01 inside if-condition");
Console.WriteLine("Separate Line 01 after if-condition");
Console.WriteLine("Separate Line 02 after if-condition");

In this case whether you want or not compiler will consider the line "Separate Line 01 after if-condition" as part of the if statement. As condition is false this line will not execute and if you continue the commenting the line this situation will carry over to next line.

Let's see the below example to understand it more clearly. This example is same as in the previous section example. What we are doing here is that checking whether the value assigned in variable is equals 1, if so then increment the value assigned in variable "b" by 1 and replace the value of "c" with new value.

using System;
 
namespace IfCondition
{
    class Program
    {
        static void  Main(string[] args)
        {
            int a = 1, b = 2, c = 3;            
 
            if (a == 2) //Statement false, should not execute following lines            
                b = b + 1; //Not executing this line
                c = 5;    //But executing this line, which is wrong, not considering part of if condition        
             
            Console.WriteLine("b: " + b.ToString());
            Console.WriteLine("c: " + c.ToString());
             
            Console.ReadLine();
        }
    }
}

If we consider example in "With Curly braces" section as the if condition is false our expected output "b=2" and "c=3". As there is no braces compiler is considering immediate line after it is the part and next line is not so value of "c" is replacing by 5 which wasn't our intention.

Conclusion

So as you can see for multiple statement if we don't use curly braces for multiple statement then statement within "if" condition get executed wrong. It is okay to use without curly braces with one statement. Now we can understand why there is a saying curly braces not necessary but Recommended. Again it is each developer/team with his/her/their own conventions.