Home > C# > C# Conditionals

Conditional Statements in c#

In C# Conditionals or decision-making statements are used to make a decision based on specific condition and run the desired piece of code. And optionally another set of statements to be executed if given condition is not met.
Conditional statements in c# includes:

  1. if
  2. if-else
  3. switch statement
  4. conditional operator

We can do nesting of all these conditional statements as well.

If

We use if statement to test a condition. i.e. when the condition is true then the compiler executes the statements inside the body of this block.
Basic syntax is

if(condition)
{
     //code to be run when given condition is true
}

Example program

using System;

namespace conditionals
{
     class Program
     {
          static void Main(string[] args)
          {
               int x;
               Console.WriteLine("Please enter a value : ");
               x = Convert.ToInt32(Console.ReadLine());
               if(x > 0)
               {
                    Console.WriteLine("Entered Value is Positive!!!!");
               }
          }
     }
}

Output
When given condition is true
Conditional Statements in c# - if condition true
When given condition is false
Conditional Statements in c# - if condition false

In the program above we are checking if the entered number is greater than 0 or not. If the condition is true i.e. greater than 0 the compiler displays a message telling the user that entered a number is positive as shown in image 1.
In the 2nd image, we take input and the user enters a negative value i.e. less than zero so the compiler will not execute the statements inside if the block.

Nested If statements
Nested if statements are one or more if statement/s inside another if statement/s.
The basic syntax is:

if(condition)
{
     //code to be run when given condition is true
     if(condition)
     {
          //code to be run when given condition is true
          if(condition)
          {
              //code to be run when given condition is true
              .
              .
              .
          }
     }
}

In nested if statements compiler checks the outer most if statement first and then the statement inside that if and so on. i.e. if the outermost condition is false it doesn’t matter whether inner conditions are true or false they will not be executed.
Example program

using System;

namespace conditionals
{
    class Program
    {
        static void Main(string[] args)
        {
            int x;
            Console.WriteLine("Please enter a value : ");
            x = Convert.ToInt32(Console.ReadLine());
            if (x > 0)
            {
                Console.WriteLine("Entered Value is Positive!!!!");
                if(x > 10)
                {
                    Console.WriteLine("Entered Value is greater than 10!!!!");
                }

            }
        }
    }
}

Output
C# nested if

C# nested if

C# nested if

In the above-written program, we have shown three outputs. The first image shows that both the conditions are true hence we have two messages displayed.
In the 2nd image, only one condition is true i.e. outermost condition so we have the message for that condition is shown. And inner if a condition is wrong so statement/s inside this if is not executed.
In the 3rd image, we have nothing shown as our outermost condition is false and it doesn’t matter that condition of inner if is true or not. Compiler will not execute those statements inside its body.

if-else

This block is same as if but it includes another optional portion of code as well. It is like if the condition is true do this otherwise do this.
Basic syntax is

if(condition)
{
     //code to be run when given condition is true
}
else
{
     //code to be run when given condition is false
}

Below example shows us it’s working.
Example Program

using System;

namespace conditionals
{
    class Program
    {
        static void Main(string[] args)
        {
            int x;
            Console.WriteLine("Please enter a value : ");
            x = Convert.ToInt32(Console.ReadLine());
            if (x > 0)
            {
                Console.WriteLine("Entered Value is Positive!!!!");
            }
            else
            {
                Console.WriteLine("Entered Value is Not Positive!!!!");
            }
        }
    }
}

Output
C# if else

C# if else

In the example when a user entered 10 which is greater than 0 our program displayed the message that Entered value is positive i.e. condition is true and statement inside the if block is run. But when the user entered -150 which is less than 0 our program shows the message that entered value is not positive. i.e. condition is not met and statement inside the else block is executed.
Hence only on the two blocks (if & else) can run at a time but not both at the same time.

Nested If-else statements
Nested if else statements work exactly like nested if statements. It will check if the first condition is true and run the set of statements written inside that block. And if the condition is not true another condition is given with else statement as else if and that condition is checked and so on.
Basic Syntax is

if(condition)
{
     //code to be run when given condition is true
}
//condition to be checked when the first condition is false
else if (condition)
{
     //code to be run when given condition is true
}
else
{
     .
     .
     .
}

Example program

using System;

namespace conditionals
{
    class Program
    {
        static void Main(string[] args)
        {
            int x;
            Console.WriteLine("Please enter a value : ");
            x = Convert.ToInt32(Console.ReadLine());
            if (x > 0)
            {
                Console.WriteLine("Entered Value is Positive!!!!");
            }
            else if (x < 0)
            {
                    Console.WriteLine("Entered Value is negative!!!!");
            }
            else
            {
                Console.WriteLine("Entered Value is Zero!!!!");
            }
        }
    }
}

Output
nested if else

nested if else

nested if else

For the above-written program, we have three outputs.
Image 1 shows that when the first condition is true compiler will not execute the other blocks of statements.
2nd Image shows that when the first condition is not true compiler checks the second condition inside else if and displays the message.
In the 3rd image, we have, when none of the above conditions are true. Compiler executes the else block.

Switch Statement

Another conditional statement available in c# is switch statement. It provides a mechanism to run a particular block of code based on some value in a convenient manner.
Basic Syntax is:

switch (choice)
{
     case 1:
     {
          //code to be run
          break;
     }
     case 2:
     {
           //code to be run
     break;
     }
     .
     .
     .
     default:
     {
          //code to be run
     }
}

Here 1 & 2 written with the case are constant expressions to be checked against choice given in switch statement.

Break: The programmer uses the break statement in every case to get out of switch statement when the condition of a particular case is true and compiler executes the statements of that case. Otherwise, all below statements will also run. This is optional.
Default: The compiler executes the default block if none of the cases are true.
Example Program

using System;

namespace @switch
{
    class Program
    {
        static void Main(string[] args)
        {
            int x;
            Console.WriteLine( "Please Enter Value : ");
            x = Convert.ToInt32(Console.ReadLine());
            switch (x)
            {
                case 0:
                {
                     Console.WriteLine("Entered Number is zero\n");
                     break;
                }
                default:
                {
                     Console.WriteLine("Entered Number is non zero\n");
                     break;
                }
            }
        }
    }
}

Output
C# switch

C# switch

Another example

using System;

namespace @switch
{
    class Program
    {
        static void Main(string[] args)
        {
            char ch;
            Console.WriteLine("Please Enter Value : ");
            ch = Convert.ToChar(Console.Read()); 
            switch (ch)
            {
                case 'a':
                {
                     Console.WriteLine("Entered Character is vowel");
                     break;
                }
                case 'e':
                {
                     Console.WriteLine("Entered Character is vowel");
                     break;
                }
                case 'i':
                {
                     Console.WriteLine("Entered Character is vowel");
                     break;
                }
                case 'o':
                {
                     Console.WriteLine("Entered Character is vowel");
                     break;
                }
                case 'u':
                {
                     Console.WriteLine("Entered Character is vowel");
                     break;
                }
                default:
                {
                     Console.WriteLine("Entered Character is not vowel");
                     break;
                }
            }
        }
    }
}

We can write the above program in a more convenient way as:

using System;

namespace @switch
{
    class Program
    {
        static void Main(string[] args)
        {
            char ch;
            Console.WriteLine("Please Enter Value : ");
            ch = Convert.ToChar(Console.Read()); 
            switch (ch)
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                {
                     Console.WriteLine("Entered Character is vowel");
                     break;
                }
                default:
                {
                     Console.WriteLine("Entered Character is not vowel");
                     break;
                }
            }
        }
    }
}

Both above-written programs will work exactly same.
Output

C# switch

C# switch

Nested Switch Statements
Nested switch statements mean one or more switch statements in case/s of another switch statement/s.
Basic syntax is

switch (choice)
{
     case 1:
     {
           //code to be run 
          switch (choice)
          {
               case 1:
               {
           //code to be run
                    break;
               }
               case 2:
               {
           //code to be run
                    break;
               }
               .
               .
               .
               default:
               {
           //code to be run
               }
          }
           break;
     }
     case 2:
     {
           //code to be run
     break;
     }
     .
     .
     .
     default:
     {
           //code to be run
     }
}

Example Program

using System;

namespace @switch
{
    class Program
    {
        static void Main(string[] args)
        {
            char gender;
            char maritalStatus;
            Console.WriteLine("Please Enter Gender : ");
            gender = Convert.ToChar(Console.ReadLine());
            Console.WriteLine("Please Enter Marital Status : ");
            maritalStatus = Convert.ToChar(Console.ReadLine());
            switch (gender)
            {
                case 'M':
                case 'm':
                {
                        switch (maritalStatus)
                        {
                            case 'M':
                            case 'm':
                                {
                                    Console.WriteLine("Person is Male and Maried.");
                                    break;
                                }
                            case 'U':
                            case 'u':
                                {
                                    Console.WriteLine("Person is Male and Un-Maried.");
                                    break;
                                }
                            default:
                                {
                                    Console.WriteLine("Wrong Value entered!!!!");
                                    break;
                                }
                        }
                        break;
                    }
                case 'F':
                case 'f':
                    {
                        switch (maritalStatus)
                        {
                            case 'M':
                            case 'm':
                                {
                                    Console.WriteLine("Person is Female and Maried.");
                                    break;
                                }
                            case 'U':
                            case 'u':
                                {
                                    Console.WriteLine("Person is Female and Un-Maried.");
                                    break;
                                }
                            default:
                                {
                                    Console.WriteLine("Wrong Value entered!!!!");
                                    break;
                                }
                        }
                        break;
                    }
                default:
                    {
                        Console.WriteLine("Wrong Value entered!!!!");
                        break;
                    }
            }
        }
    }
}

Output
C# nested switch

C# Ternary operator

Conditional Operator also called Ternary operator is another Decision-making statement used in C#. Ternary operator helps a convenient way to write an expression that yields two possible values depending on the condition.
The basic syntax for C# ternary operator is:

condition ? Expression1: expression2

The ternary operator will check the condition and if the condition is true it will use the first expression otherwise it will use the 2nd expression. Though we can replace the expressions by other conditions as well. Below example will help us understanding the c# ternary operator in a better way.

Example Program

using System;

namespace @switch
{
    class Program
    {
        static void Main(string[] args)
        {
            int no = 0, no1 = 0, no2 = 0;
            Console.WriteLine("Please Enter No 1 : ");
            no1 = Convert.ToInt32(Console.ReadLine()); 
            Console.WriteLine("Please Enter No 2 : ");
            no2 = Convert.ToInt32(Console.ReadLine()); 
             // using conditional operator
            no = (no1 > no2) ? no1 : no2;
            Console.WriteLine("Maximum Number is : " + no);
        }
    }
}

Output
C# Conditionals - C# ternary operator example
Another Example

using System;

namespace @switch
{
    class Program
    {
        static void Main(string[] args)
        {
            int no = 0, no1 = 0, no2 = 0, no3=0;
            Console.WriteLine("Please Enter No 1 : ");
            no1 = Convert.ToInt32(Console.ReadLine()); 
            Console.WriteLine("Please Enter No 2 : ");
            no2 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please Enter No 2 : ");
            no3 = Convert.ToInt32(Console.ReadLine());

            // using conditional operator
            no = (no1 > no2) ? no1 : (no2 > no3) ? no2 : no3;
            Console.WriteLine("Maximum Number is : " + no);
        }
    }
}

Output
C# Conditionals - C# ternary operator example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.