Hi have a question,i know it is always a good practice to include default in the switch,but can it be omitted in this case? As i see it would be redundant.

static void Main(string[] args)
        {
            bool quit = false;
            do
            {
                var option = ShowMenu();
                switch (option)
                {
                    case 1:
                        CreateStudentData();
                        break;
                    case 2:
                        DisplayStudentData();
                        break;
                    case 3:
                        DisplayDataByIdReversed();
                        break;
                    case 4:
                        quit = true;
                        Console.WriteLine(  "Thanks for using the app.\n" );
                        break;
                }
            } while (!quit);
        }
     public static int ShowMenu()
        {
            Console.WriteLine("\t\t1 Create student data");
            Console.WriteLine("\t\t2 Display student data");
            Console.WriteLine("\t\t3 Display student data by reverse ID order");
            Console.WriteLine("\t\t4 Exit");
            Console.WriteLine("\n");
            int option;
            while (true)
            {
                Console.Write("\t\tEnter Option Here: ");
                try
                {
                    option = Int32.Parse(Console.ReadLine());
                    if (option < 1 || option > 4)
                    {
                        throw new Exception();
                    }
                }
                catch
                {
                    Console.WriteLine("Invalid input,must be choice 1-4");
                    continue;
                }
                break;
            }
            return option;
        }

Recommended Answers

All 3 Replies

As you are preventing any other numbers then covered by your cases, a default is not needed here. In fact it would never ever be executed.
If you are not sure about which case can come up, it is best to use a default.

can it be omitted in this case?

Yes, a default case can be omitted if you already cover all of the possible cases, or not executing any of the cases wouldn't be damaging.

Hello arturLIT!
You don't always need a default statement in your switch statements. The default is used as a "catch all" when you want to control how the application responds in the event your case statements aren't met. Otherwise, you can just let the process "fall through" and continue on with the next line of code after the switch block. Hope this helps.

Tekkno

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.