Select Case in C#: An Elegant Decision Making Construct

c# exception handlingC# is a modern, simple and general purpose programming language. It is an object oriented language based on C++. C# has features similar to that found in Java. It does not directly support multiple inheritance. However C# uses interfaces to implement multiple inheritance. It is part of Microsoft’s .NET initiative and is designed to be platform independent. C# programs are compiled into Microsoft Intermediate Language(MSIL). It is relatively easy for C,C++ and Java developers to learn C#. One of this language’s important feature is garbage collection. C# supports the core object oriented concepts such as encapsulation, inheritance and polymorphism.

In this intermediate level tutorial, we walk you through C# select case. We assume that you are familiar with the basics of C#. Else you can take this course to learn the fundamentals of C# programming.

A Simple C# Program

using System;
namespace ExampleApplication
class Example
{
static void Main( string [] args)
{
/* Introductory C# program*/
Console.WriteLine("Welcome Everybody");
}
}

Let’s take a simple C# program to get you started on the basic constructs of C#. You’ll need this to write any program in C#. The using keyword includes the System namespace in the program. A C# program may have multiple using statements. A namespace contains classes. The namespace ExampleApplication contains the class Example. The class keyword declares Example to be a new class. By definition a class consists of data and methods. Classes may contain more than one method. The execution of C# programs starts with the main() function. Comments in this language start with ‘/* and end with ‘*/’. The compiler leaves the comments untouched. The static keyword ensures that there is only one instance of main() method which is class specific. Objects created with this class will not have object specific instances of the main() method. The main() method’s return type is void. This means the method will not return any value. Inside the main() method the class Console call its member function WriteLine to print the string “Welcome Everybody” on the output screen.

C# is case sensitive. It makes a distinction between uppercase and lowercase. In C# file names can be different from the class name. This language uses the semicolon as a terminator for statements. Learn more on writing your own C# programs with this course.

Introduction to Select Case

The select case, is more commonly called the switch case in C#, because it actually switches between multiple cases. A switch statement contains a list of values and if the variable matches a value in the list, that case is selected for execution. The following is the syntax for switch case

switch(variable){
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;
/*There is no restriction on the number of case statements*/
default :
statement(s);
}

A switch statement does not restrict the number of case statements. The data type of the switch variable should be the same as the values in the different cases. In case of match between the switch variable and a case value, then the statements in that case will be executed. It will go on till a break statement is encountered. The break statement will transfer program control to the line after the switch statement. The break statement is not mandatory in the switch statement. The latter has an optional default case. The default case can only be put at the end of the switch statement. When no case is true, the default statement can be used to execute desired statements.

Example 1: A Sample C# Switch Case Program

using System;
class Program1
{
static void Main()
{
int value = 4;
switch (value)
{
case 1:
Console.WriteLine(1);
break;
case 2:
Console.WriteLine(2);
break;
case 3:
Console.WriteLine(3);
break;
case 4:
Console.WriteLine(4);
Break;
case 5:
Console.WriteLine(5);
break;
default:
Console.WriteLine(“None of the above”);
break;
}
}
}

In this program, switch will evaluate the integer variable value. As it holds value 4, program control will transfer to case 4. The Console.Writeline() method will print 4 on the output screen. The break statement will cause control to come out of switch. See more real world examples with select case in this course.

Example 2: Program Demonstrating Clubbing Multiple Cases

using System;
class Program2
{
static void Main(string[] args)
{
int switchValue = 3;
switch (switchValue)
{
case 0:
case 1:
Console.WriteLine("First set");
break;
case 2:
Console.WriteLine("Second Set");
break;
case 9 - 6:
Console.WriteLine("Third Set");
break;
default:
Console.WriteLine("Default case");
break;
}
}
}

Here we see that multiple case labels can be stacked together. If you don’t use a break to terminate your case, the code will fall through in execution to the next switch case. That means that if any case does not have the break statement, it wont exit the switch case, instead, it will execute the next case. Here, Case 0 and Case 1, both fall back to the same print statement. Cases 9 to 6 evaluates to the third set. The default case is executed only if the previous cases do not satisfy the variable value.

Example 3 : Program Demonstrating Character Select Cases

using System;
class Program3
{
static void Main()
{
char input1 = 'd';
string value1 = SwitchChar(input1);
Console.WriteLine(value1);
}
static string SwitchChar(char input)
{
switch (input)
{
case 'A'
case 'a':
{
return "Apple";
}
case 'B'
case 'b':
{
return "Banana";
}
case 'C'
case 'c':
{
return "Cherry";
}
case 'D'
case 'd':
{
return "Dates";
}
default:
{
return "Invalid Option";
}
}
}
}

Here the switch statement tests for equality of character values. Note that both lowercase and uppercase versions of characters are stacked together, and each character has to be specified in single quotes. Learn more about using character variables in C# with this course.

Example 4 : Program Code to Demonstrate Usage of Strings in Select Case

Console.WriteLine("Do you like coffee ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "yes":
case "maybe":
Console.WriteLine("Nice to hear that");
break;
case "no":
Console.WriteLine("Maybe you like some other drink!");
break;
default:
Console.WriteLine("I'm sorry, I didn't understand that!");
break;
}

The above program uses switch against string values. In case of string not matching to any of the cases program control transfers to the default label.

Example 5: Program to Perform Simple Arithmetic Using Select Case

using System;
namespace myprogram
{
class Program3
{
static void Main(string[] args)
{
int yourchoice, number1, number2;
float result;
newlabel:
Console.WriteLine("\n\tMenu");
Console.WriteLine("\nPress 1 for adding");
Console.WriteLine("Press 2 for subtracting");
Console.WriteLine("Press 3 for multipliying");
Console.WriteLine("Press 4 for Dividing");
Console.Write("\n\nInput the first number:\t");
number1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the second number:\t");
number2 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter your choice:\t");
yourchoice = Convert.ToInt32(Console.ReadLine());
switch (yourchoice)
{
case 1:
result = number1 + number2;
Console.WriteLine( result);
break;
case 2:
result = number1 - number2;
Console.WriteLine( result);
break;
case 3:
result = number1 * number2;
Console.WriteLine(result);
break;
case 4:
result = (float)number1 / number2;
Console.WriteLine( result);
break;
default:
Console.WriteLine("\nInvalid choice                   Please try again.");
goto newlabel;
}
Console.ReadLine();
}
}
}

Here first a menu is displayed. Then the user is prompted to select the desired arithmetic operation. The switch statement accordingly transfers program control to the appropriate case. In case of error in choice goto keyword is used to transfer control to the beginning of the program.

Hope this article helped you understand select cases in C# better. Of course, select cases are just part of the C# language. To get a more holistic view, you should take this comprehensive course on C#.