C# Case Statement : Switching Between Multiple Cases

c# case statementC# is a simple, modern, general purpose and object oriented language developed by Microsoft. It is part of the .NET Framework and can be compiled in a host of different computer platforms. Since it based on the constructs of Java and C++, C# is a component oriented language, and quite easy to learn (you can learn the basics in under one hour, with this course!). In this tutorial, we take a deep dive C# case statement – what it does and how to use it. This requires a basic understanding of C#. If you’re new to it, you may want to first take this beginners course.

Just to make sure we’re all on board, we’ll first quickly walk you through how to write a simple C# program, so that it’s easier for you to understand the switch case examples we get into later.

A Simple C# program

A C# program generally consists of the following parts

  • Namespace declaration
  • A class
  • Class methods
  • Class attributes
  • A Main method
  • Statements and Expressions

Let’s take a look at an example

using System;
namespace GoodMorningApplication
{
class GoodMorning
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Good Morning");
Console.ReadKey();
}
}
}

The using keyword includes the System namespace in the program. A program can have multiple using statements. A namespace is nothing but a collection of classes. The GoodMorningApplication namespace contains the class GoodMorning. The latter contains data and method definitions. Usually classes contains more than one method. Note that methods define the behavior of the class. However the GoodMorning class has only one method Main. The Main method is the entry point for all C# programs. The content betweem’/*’ and ‘*/’ are comments which will be ignored by the compiler.Console. Readkey() makes the program wait for a key press and prevents the screen from running and closing quickly when the program is launched. WriteLine is one of the methods of the Console class defined in the System namespace. It causes the message “Good Morning” to be displayed on the screen.  To see more examples of C# programs, check out this C# tutorial for beginners.

Case Statement

The case statement is part of the switch statement. This keyword is used inside switch statements of the C# programming language. It specifies a constant to be matched in the switch selection statement. Note that cases can be stacked and combined. Remember that case is specific to the switch statement. It is a method to specify constants that match the selection in the switch statements. Only in the scenario of the case constants being matched will the code blocks following a specific case statement be executed.

The switch statement is a control statement which selects a switch section to execute from a list of candidates. Note that a switch statement includes one or more switch sections. Also each switch section contains one or more case labels followed by one or more statements. The example given below shows a simple switch statement that has three switch sections. Each switch section has one case label such as case 1 and two statements.

Example 1: Simple Case Statement

int value = 1;
switch (value)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}

Note that each case label specifies a constant value. The switch statement transfers control to the switch section whose case label matches the value of the switch expression. In case no case label contains a matching value, control is transferred to the default section if it exists. In case of no default section, no action is taken and control is transferred outside the switch statement.

Remember that a switch statement can include any number of  sections and each section can have one or more case labels. Note that no two case labels may contain the same constant value. Execution of the statement list in the selected switch section begins with the first statement and proceeds through the statement list until a jump statement such as break, goto case, return or throw is reached. Here control is transferred outside the switch statement or to another case label.

Example 2: Program that Switches on Char Case Statements

using System;
class Example
{
static void Main()
{
char newinput1 = char.Parse("s");
string newvalue1 = SwitchChar(newinput1);
 char newinput2 = char.Parse("c");
string newvalue2 = SwitchChar(newinput2);
 Console.WriteLine(newvalue1);
Console.WriteLine(newvalue2);
Console.WriteLine(SwitchChar('T'));
}
 static string SwitchChar(char input)
{
switch (input)
{
case 'a':
{
return "Area";
}
case 'b':
{
return "Box";
}
case 'c':
{
return "Cat";
}
case 'S':
case 's':
{
return "Spot";
}
case 'T':
case 't':
{
return "Test";
}
case 'U':
case 'u':
{
return "Under";
}
default:
{
return "Deal";
}
}
}
}
Output
Spot
Cat
Test

The example shows the switch statement used with char variable. This program takes an arbitary char value which is returned from the char.Parse method and passes the char as an argument to the SwitchChar method. The latter uses the switch control statement. In other words it tests if the char is equal to known character values or not. Note that the default case deals with all other cases. The three cases S,T and U in the switch statement are stacked on the lowercase equivalents which is one way to normalize data and treat ‘u’ and’U’ equivalently. Alternatively we can use the char.ToLower method here.

 

Example 3: Program that switches on enum case statements

using System;
 enum Priority
{
Zero,
Low,
Medium,
Important,
Critical
};
 class Example
{
static void Main()
{
Priority priority = Priority.Zero;
 if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
{
priority = Priority.Critical;
}
 if (IsImportant(priority))
{
Console.WriteLine("The problem is important.");
}
 priority = Priority.Low;
Console.WriteLine(IsImportant(priority));
 priority = Priority.Important;
Console.WriteLine(IsImportant(priority));
}
 static bool IsImportant(Priority priority)
{
switch (priority)
{
case Priority.Low:
case Priority.Medium:
case Priority.Zero:
default:
return false;
case Priority.Important:
case Priority.Critical:
return true;
}
}
}
Output
(First line is only written on Monday.)
The problem is important.
False
True

Switch case can act upon enum values. Enums are useful if the program has to use magic constants. In the above program the IsImportant method uses five explicit cases and a default case. Here the switch tests the parameter that is an enum of type Priority. True is returned if the Priority value is Important or Critical. Otherwise false is returned. You can learn more about enums in C# with this course.

Example 4: Program that Uses Switch on String Case Statements

 using System;
class Example
{
static void Main()
{
Console.WriteLine(IsMoth("Ash Pug"));
Console.WriteLine(IsMoth("Dot Net Perls"));
}
 static bool IsMoth(string value)
{
switch (value)
{
case "Atlas Moth":
case "Beet Armyworm":
case "Indian Meal Moth":
case "Ash Pug":
case "Latticed Heath":
case "Ribald Wave":
case "The Streak":
return true;
default:
return false;
}
}
}
Output
True
False

We can use the switch statement to test whether a string is one of a set of values. It is possible to do this without the manual creation of any data structures such as an array or Dictionary. In this program, IsMoth contains a switch case with seven moth names in it. In case any of those strings are equivalent to the parameter it returns true and you know you have a moth name.

Note that this is just one small construct of C#. You need to have a holistic understanding of the language to write your own programs. We recommend you take this full course to better understand the different aspects of programming with C#.