By 22/07/2015 8 Comments

C# Nested Switch Statements

  • Like nested ifs, there is also a nested switch statement.
  • In nested switches, a switch statement is declared inside other switch and so on.
  • This is called inner or nested switch, 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 can not be logged in and also can be view invalid messages.

Example:

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 = "admin321";

            // An outer switch statement is declared.
            switch (userName)
            { // Outer switch is started.

                // This keyword (case) is associated with its outer switch statement.
                case "admin":

                    // Inner switch statement is declared.
                    switch (userPassword)
                    {
                       // This keyword (case) is associated with its inner switch statement.
                        case "admin321":
                            Console.WriteLine("You have successfully authenticated...");
                            break;

                        // This keyword (default) is associated with its inner switch statement.
                        default: 
                            Console.WriteLine("Invalid passwrod!");
                            break;

                    } // Inner switch statement is closed.
                    break;

                // This keyword (default) is associated with its outer switch statement.
                default: 
                    Console.WriteLine("Invalid user name!");
                    break;
            } // Outer switch statement is closed.
     
            Console.ReadKey();

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

    /*
   The Output will be:
   You have successfully authenticated...
  */
}





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 .