mardi 1 octobre 2019

Turning If / else if / else into Switch / Case in C#

I'm showing some folks an intro to arrays and if / else if / else statements. I want to show them how to convert their if / else if / else statements into Switch / Case. What's the best way to go about this? I have heard that Switch / Case is much more efficient when dealing with a broader range of choices.

Here is the example I am making for them and in the code.

{
        int []  acct = new int [3];

        acct[0] = 8675309;
        acct[1] = 8675310;
        acct[2] = 8675311;

        Console.WriteLine("Enter your account number");
        int myacct = int.Parse(Console.ReadLine());
        //int myacct = Convert.ToInt32(Console.ReadLine());<--This works too
        if (myacct == acct[0])
        {
            Console.WriteLine("What is your name?");
        }
        else if (myacct == acct[1])
        {
            Console.WriteLine("What is your name?");
        }
        else if (myacct == acct[2])
        {
            Console.WriteLine("What is your name?");
        }
        else
        {
            Console.WriteLine("Sorry you don't have access");
        }

        string name = Console.ReadLine();

        string[] names = new string[3] { "Jenny", "Roberto", "Sally" };
        /*  This shows them how to tighten the code up compaired to the technique we used above
        names[0] = "Jenny";
        names[1] = "Roberto";
        names[2] = "Sally";
        */

        //I'd like to make the following code into a Switch and Case type statement instead of using else if.


        /*
        if (myacct == acct [0] && name == "Jenny")
        {
            Console.WriteLine("Welcome "+names[0] + "!");
        }


        else if (myacct == acct[1] && name == "Roberto")
        {
            Console.WriteLine("Welcome Roberto" + names[1] + "!");
        }
        else if (myacct == acct[2] && name == "Sally")
        {
            Console.WriteLine("Welcome Sally" + names[2] + "!");
        }
        else
        {
            Console.WriteLine("Account number and Names do not match");
        }
        */
    }
}

Aucun commentaire:

Enregistrer un commentaire