Nested If Else

In the preceding example, you checked for three conditions involving the value of var1 . This covered all possible values for this variable. Sometimes, you might want to check for specific values — for example, if var1 is equal to 1, 2, 3, or 4, and so on. Using code such as the preceding can result in annoyingly nested code:

Example

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int var1 = 3;
            if (var1 == 1)
            {
                // Do something.
            }
            else
            {
                if (var1 == 2)
                {
                    // Do something else.
                }
                else
                {
                    if (var1 == 3 || var1 == 4)
                    {
                        // Do something else.
                    }
                    else
                    {
                        // Do something else.
                    }
                }
            }
        }
    }
}