C# if else statement

C# if else statement

1 - C# if...else Statement

The if statement evaluates the code if the condition is true but what if the condition is not true, here comes the else statement. It tells the code what to do when the if condition is false.

The syntax for this construct is as follows:

if (condition)
{
  // block of code to be executed if the condition is True
} 
else 
{
  // block of code to be executed if the condition is False
}

Using the above syntax, we can now extend our previous example to display a different message if the comparison expression evaluates to be false:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10;

            if (x > 8)
            {
                Console.WriteLine("x is greater than 8!");
            }
            else
            {
                Console.WriteLine("x is less than 8!");
            }
        }
    }
}

In this case, the second WriteLine statement would execute if the value of x was less than 8.

*** Within an else clause, you can nest another if statement:

if (2 + 2 == 5)
       Console.WriteLine("Does not compute");
else
       if (2 + 2 == 4)
            Console.WriteLine("Computes");    // Computes

 

2 - C# if else Flow Diagram

The following flowchart illustrates how the if else statement works:

C# if else Flow Diagram

3 - C# if ... else if .. Statements

You can also chain multiple if-else statements together to create more complex conditionals.

Syntax:
The syntax of an if...else if...else statement in C# is:

if(boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
   /* Executes when the boolean expression 3 is true */
}
else 
{
   /* executes when the none of the above condition is true */
}

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            /* local variable definition */
            int a = 100;

            /* check the boolean condition */
            if (a == 10)
            {
                /* if condition is true then print the following */
                Console.WriteLine("Value of a is 10");
            }

            else if (a == 20)
            {
                /* if else if condition is true */
                Console.WriteLine("Value of a is 20");
            }

            else if (a == 30)
            {
                /* if else if condition is true  */
                Console.WriteLine("Value of a is 30");
            }

            else
            {
                /* if none of the conditions is true */
                Console.WriteLine("None of the values is matching");
            }
            Console.WriteLine("Exact value of a is: {0}", a);
            Console.ReadLine();
        }
    }
}

Output:

When the above code is compiled and executed, it produces the following result:

C# if ... else if .. Statements

 

4 - C# else Statement

Use the else statement to specify a block of code to be executed if the condition is False.

The else statement can come only after if or else if statement and can be used only once in the if-else statements. The else statement cannot contain any condition and will be executed when all the previous if and else if conditions evaluate to false.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 20, j = 20;

            if (i > j)
            {
                Console.WriteLine("i is greater than j");
            }
            else if (i < j)
            {
                Console.WriteLine("i is less than j");
            }
            else
            {
                Console.WriteLine("i is equal to j");
            }
            Console.ReadLine();
        }
    }
}

Output:

C# else Statement example

 

 

5 - C# Nested if Statements

It is always legal in C# to nested if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).

Syntax:

The syntax for a nested if statement is as follows:

if( boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
   if(boolean_expression 2)
   {
      /* Executes when the boolean expression 2 is true */
   }
}

You can nest else if...else in the similar way as you have nested if statement.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            //* local variable definition */
            int a = 100;
            int b = 200;

            /* check the boolean condition */
            if (a == 100)
            {
                /* if condition is true then check the following */
                if (b == 200)
                {
                    /* if condition is true then print the following */
                    Console.WriteLine("Value of a is 100 and b is 200");
                }
            }
            Console.WriteLine("Exact value of a is : {0}", a);
            Console.WriteLine("Exact value of b is : {0}", b);
            Console.ReadLine();
            Console.ReadLine();
        }
    }
}

Output:

C# - Nested if Statements

 

6 - C# Short Hand If...Else

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. 

It is often used to replace simple if else statements:

variable = (condition) ? expressionTrue :  expressionFalse;

Instead of writing:

int time = 30;
if (time < 28) 
{
  Console.WriteLine("Good day.");
} 
else 
{
  Console.WriteLine("Good evening.");
}

You can simply write:

int time = 30;
string result = (time < 28) ? "Good day." : "Good evening.";
Console.WriteLine(result);

 

6 - Conditional Operators in C# if statement

In C#, you can use the conditional OR (||) and conditional AND ( && ) operators in if statements to combine multiple conditions into a single expression.

01. Conditional or ( || )

 

The || (conditional OR) operator returns true if either of the conditions is true, and false if both conditions are false. The basic syntax of using the operator in an if statement is as follows.

Syntax:

if (condition1 || condition2)
{
  // Run this part  if condition1 is true or condition2 is true
}

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int mark = 55;
            int attendance = 65;
            if (mark >= 60 || attendance >= 75)
            {
                Console.WriteLine("You passed the course.");
            }
            else
            {
                Console.WriteLine("You failed the course.");
            }
            Console.ReadLine();
        }
    }
}
02. Conditional and (&&)

 

The && (conditional AND) operator returns true if both conditions are true, and false if either of the conditions is false. The basic syntax of using the && operator in an if statement is as follows.

Syntax:

if (condition1 && condition2)
{
  // Run this part  if condition1 is true and condition2 is true
}

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int mark = 75;
            int attendance = 80;
            if (mark >= 60 && attendance >= 75)
            {
                Console.WriteLine("You passed the course.");
            }
            else
            {
                Console.WriteLine("You failed the course.");
            }
            Console.ReadLine();
        }
    }
}

Output:

C# conditional AND