Enum – How to Use a Switch Statement with Enum Efficiently

enumswitch statement

I would like to know how I can use a switch statement with enum values for the following scenarios:

I am making a small program for a flight reservation system. The program is meant to enter certain details about the passenger. The program also restricts the user to choose destinations other than the following 3 destinations. Once destination is chosen, the flight number is supposed to be automatically assigned.
The user will choose one of three destinations and program will assign an appropriate Flight No for the passenger.

The Flight No will be assigned as below:

     Destination                    Flight No.
      London                            201
      Frankfurt                         233
      Berlin                            241

So let's say I make an enum of destinations, then how can I use switch statement here? This isn't a homework. I am doing it just for the sake of exploring.

Best Answer

Your scenario doesn't sound like an appropriate use for an enumeration. Also, unless the values never change, this should be data driven.

If the values never change, then a key-value pair is more appropriate where the destination is the key and the flight number is the value. This would eliminate any need for a switch statement, as the key can be used to directly and efficiently locate the value.

if you really want to use an enum, then the switch statement in C# would be something like:

int flightNumber;
Destination selection = // some value collected from user input;

switch( selection )
{
    case Destination.London:
        flightNumber = 201;
    break;

    // etc.
}