C# Nested if statement


In the previous tutorials, we discussed C# if statement, C# if-else statement and also if ..else if ..else statement . In this C# tutorial, we are going to learn nested if statement in C# language. The C# language supports nested if statement. The meaning of Nested if statement, you can use if or else if statement inside the if or if-else statement.

First of all, if statement handles the main conditional process. If the condition is true then compiler checks another if statement inside that parent if statement. if the child if condition evaluated to false then execute the else part in C# programming.

Let's understand the nested if statement.

 


Syntax of C# nested if statement.


if(condition1) {
   /* Executes when the condition1 is true */

   if(condition2) {
      /* Executes when the condition2 is true */
   }
   if(condition3) {
      /* Executes when the condition3 is true */
   }

}

In the above nested if statement, you can see the three if condition inside the one parent if condition.

We can nest else if else in a similar way.

Let's create an example in C# programming for nested if statement.


using System;

namespace NestedifStatement{

  public class Program {
   
     public static void Main(string[] args) {
        
         int x = 45;
         int y = 90;
       
         if (y>x)  {
            
            /* if condition is true then check the below condition */
            if (y >x)  {
               /* if condition is true then print the following */
               Console.WriteLine("y is greater than x . y="+y+ ",x="+x);
            }
         }
       if (x>y) {
            
            /* if condition is true then check the below conditiong */
            if (y>x) {
               /* if condition is true then print the following */
               Console.WriteLine("y is greater than x . y="+y+ ",x="+x);
            }
         }
		 
         Console.ReadLine();
      }
   }
}

Output - 

Output -
 y is greater than x . y=90,x=45 

In the above C# nested if statement example, we declared two variables with values and create two-parent if conditions and two child if conditions. First parent if the statement is evaluated to true. The compiler checks another condition inside the first parent if block and execute the code.

 

The second parent if the condition is elevated to false. The compiler never checks child if condition.
This is known as nested if statement in C# programming.


Please Share

Recommended Posts:-


Live Chat

Hello! How can we assist you today?