C# Nested If Statement

In real-time, we can come across scenarios where we have to make one decision by checking multiple conditions. Using C# Nested if statements, we can write several if or else if conditions inside one if or else if condition.

The syntax of the C# Nested If Statement is

If <condition>
{
 
   If <condition>
   {
     Statements;
   }
  else if<condition>
  {
    Statements;
  }
  else
   Default statements
}
else
Default statements;

C# Nested If Statement Example

For example, let us assume that for a particular job requirement. The job profile is as follows:

  • Candidate should be from it or csc department.
  • Academic percentage >= 60
  • Age < 50

If all the above conditions are satisfied, then the person is eligible for the post. Let us write C# code for the above scenario.

using System;

namespace CSharp_Tutorial
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Enter your Department");
            string Department = (Console.ReadLine());

            if (Department.ToUpper() == "IT" || Department.ToUpper() == "CSC")
            {
                Console.WriteLine("Enter your Percentage");
                int Percentage = int.Parse(Console.ReadLine());

                if (Percentage >= 60)
                {
                    Console.WriteLine("Enter your age");
                    int Age = int.Parse(Console.ReadLine());
                    if (Age < 50)
                    {
                        Console.WriteLine("You are eligible for this post");
                    }
                    else
                        Console.WriteLine("Your age is not suitable for the requirement");
                }
                else
                    Console.WriteLine("Your Percentage is not suitable for the requirement");
            }
            else
                Console.WriteLine("Your qualification is not suitable for the requirement");
        }
    }
}

OUTPUT

C# Nested If Statement 1

In this C# Nested If Statement example, we have given Department name as ‘csc’. Since it satisfies the condition, it entered into inner if

Next, it asks for the Percentage.

The Percentage is given as 40.

Since this percentage condition failed because Percentage should be >= 60 to enter into inner if, i.e., age condition.

The compiler exit from the loop and print the else part, i.e.,

Your Percentage is not suitable for the requirement.

Let me try Percentage as 60, age as 28, and you get the different result.

C# Nested If Statement 2

Here, we have given good Percentage but the inner if statement condition age < 50 fails. So, inner else block statement printed.

C# Nested If Statement 3

This time, we have given the wrong department so that it results the main else block statement.

C# Nested If Statement 4