If like me you’ve been coding for a long time you may have begun your career using languages whose only decision making structure was “IF … THEN” or similar. My first language was BASIC, which was never the best regarded language but is easy to learn and fitted in the tiny little ROMs of early home computers.

Among the many things BASIC lacked was a SELECT/CASE statement or SWITCH/CASE. Indeed some implementations didn’t even have “IF … THEN … ELSE”, just “IF … THEN”.

Imagine my glee when I advanced from BBC BASIC to Visual Basic and there was a SELECT … CASE … ELSE. It was like being given the keys to a starship after driving a Mini for years. Well, almost.

Now that I’ve established that little things excite me think about what came next. VB.NET, C++ and C# with their SWITCH statements … and then when I thought that a language wouldn’t make me go “Oooooh!” again C# came up with the goods.

Consider this fragment of a hypothetical class:

        public static String ReturnSwitchTraditional(int n)
        {
            switch (n)
            {
                case 0:
                    return "Unknown";
                case 1:
                    return "Option 1";
                case 2:
                    return "Option 2";
                default:
                    return CustomString(n);
            };
        }

        private static String CustomString(int n)
        {
            return "Custom Option";
        }

Until discovering C#’s cool alternative I thought this was a pretty efficient way of doing things. Then I found out that this also works and it’s so much more elegant:     

public static String ReturnSwitch(int n)
        {
            return n switch
            {
                0 => "Unknown",
                1 => "Option 1",
                2 => "Option 2",
                _ => CustomString(n)
            };
        }

If this made you go Ooooh!, we can be friends.

Leave a Reply

Your email address will not be published. Required fields are marked *