By 22/07/2015 17 Comments

C# Nested if Statements

  • In this if statement form you can declare any number of if…else statements inside another if…else.
  • This is called inner or nested ifs, this form is very useful for complex programs or real world examples such as user authentication where user enters his/her name and password for authentication, that user and password must be valid, if any one from these two will be invalid user cannot be logged in.


using System;
namespace csharpBasic
    // Start class definition / declaration.
    class Program
        // Static main method void type declaration.
        static void Main(string[] args)
            // 2 string variables are initialized.
            string userName = "admin", userPassword = "admin123";

            // An outer if statement is declared.
            if (userName == "admin")
                // An inner if statement is declared.
                if (userPassword == "admin123")
                    Console.WriteLine("You have authenticated...");

                // An inner else statement is declared, this else is associated with inner if statement.
                    Console.WriteLine("Invalid Password!");
            } // End of an outer if statement.

          // An outer else statement is declared, this else is associated with outer if statement.
                Console.WriteLine("Invalid User name!");


        } // End of main method definition. 
    } // End of class. 

   The Output will be:
   You have authenticated...


  • If you use parenthesis with if…else such as if (condition) {statement 1} else {statement 2} this means you can declare more than one statements or anything else inside (else or if statement’s body) and those multiple statements will be associated with that if or else statement.
  • If you do not use parenthesis with if…else statements such as if (condition) statement 1; else statement 2; this means only single or one statement associates with that (if or else statement). It is recommended that use parenthesis with if…else statements.

Next Tutorial →

← Previous Tutorial

Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .