Table of contents >> Introduction > Nested If statements
Medium importance article

Sometimes in your programs, you will need to perform checks inside other checks. These kind of conditional processing are called nested if statements or nested if-else statements.

In common words, nesting is the process of placing a concept inside another concept. In our case, we are placing a conditional statement inside another conditional statement. The only thing you need to be careful about is the fact that every else clause corresponds to the nearest previous if clause. When dealing with nested conditional processing, you should always use code blocks as the body of the instructions, because nested conditional checks can be confusing. Here is an example of nested if statements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int hour = 7;
            int minute = 30;
            
            if (hour < 7) // first check if hour is less than 7
            {
                Console.WriteLine("It is not morning yet");
            }
            else // hour is greater than or equal to 7. Execute the nested condition checks!
            {
                if (minute < 30) // check if minute is less than 30
                {
                    Console.WriteLine("Wake up, shower, breakfast!");
                }
                else // minute is greater than or equal to 30
                {
                    Console.WriteLine("Time to go to work!");
                }
            }
            
            Console.ReadLine();
        }
    }
}

The output follows:

Time to go to work!
 
 

The concepts explained in this lesson are also shown visually as part of the following video: