C# switch case statement is a selection statement. C# switch case statement executes code of one of the conditions based on a pattern match with the specified match expression. The C# switch statement is an alternative to using the C# if else statement when there are more than a few options. The code examples in this article demonstrate various use cases of switch case statements in C# and .NET Core.
C# switch statement pairs with one or more case blocks and a default block. The case block of code is executed for the matching value of the switch expression value. The default option code is executed if the switch value doesn't match the case value.
The following is the definition of the switch..case statement.
switch (expression)
{
case expression_value1:
Statement
break;
case expression_value2:
Statement
break;
case expression_value3:
Statement
break;
default:
Statement
break;
}
The expression in the above code can be any non-null expression.
Listing 1 demonstrates a typical switch statement. A switch expression is a random number between 1 and 9. Based on the value of the expression, a case block is executed. If the value of a switch expression doesn't match the first three case values, the default block is executed.
// Generate a random value between 1 and 9
int caseSwitch = new Random().Next(1, 9);
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Value didn't match earlier.");
break;
}
Listing 1.
The case statement can be a statement of one or multiple statements or nested statements.
Listing 2 uses multiple statements in case 1.
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
DateTime date = DateTime.Today;
Console.WriteLine("Today's date is {0}", date);
if (date.Day == 2)
{
Console.WriteLine("This is the shortest month");
}
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Default case");
break;
}
Listing 2.
Using Enum in a switch statement
Let's find out if today is a weekend or a weekday. Listing 3 uses an enum in a case statement and checks if the DayOfWeek is Saturday or Sunday; it's a weekend or a work day.
// switch..case with enum
void WeekEndOrWeekDay()
{
switch (DateTime.Now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("Today is Weekend");
break;
default:
Console.WriteLine("Today is a work day.");
break;
}
}
Listing 3.
Using multiple case statements in one switch
You can execute the same code for multiple switch expression values. In the Listing 4 example, if the value is Color.Blue, Color.Black, Color.Orange, or default, the last line of code is executed.
public enum Color { Red, Green, Blue, Black, Orange }
public static void RandomConsoleBackground()
{
Color c = (Color)(new Random()).Next(0, 4);
switch (c)
{
case Color.Red:
Console.BackgroundColor = ConsoleColor.Red;
Console.Clear();
Console.WriteLine("Red");
break;
case Color.Green:
Console.BackgroundColor = ConsoleColor.Green;
Console.Clear();
Console.WriteLine("Green");
break;
case Color.Blue:
case Color.Black:
case Color.Orange:
default:
Console.WriteLine("No need to change background.");
break;
}
Listing 4.
Case Patterns
The case statement defines a pattern to match the match expression. There are two types of patterns, constant pattern and non-constant (type) pattern.
Constant pattern
The constant pattern tests whether the match expression equals a specified constant. In the case of a constant pattern, the case statement is followed by a constant value.
case constant:
Where constant is the value to test for and can be any of the following constant expressions,
- A bool literal, either true or false.
- Any integral constant, such as an int, a long, or a byte.
- The name of a declared const variable.
- An enumeration constant.
- A char literal.
- A string literal.
The constant expression is evaluated as follows,
- If the match expression and constant are integral types, the equality operator '==' is used to compare the value and returns true for the matching value.
- Otherwise, the value of the expression is determined by a call to the static Object.Equals method.
Listing 5 is an example of using a char constant in a switch statement.
// switch..case with char
void CharSwitchCase()
{
char ch = 'c';
switch (ch)
{
case 'c':
Console.WriteLine("c found!");
break;
default:
Console.WriteLine("c not found!");
break;
}
}
Listing 5.
Listing 6 is an example of using a string constant in a switch statement.
// switch..case with string
void StringSwitchCase()
{
string name = "Mahesh";
switch (name)
{
case "Mahesh":
Console.WriteLine("First name was used!");
break;
case "Chand":
Console.WriteLine("Last name was used!");
break;
default:
Console.WriteLine("No name found!");
break;
}
}
Listing 6.
Type Pattern
The switch statement can use a type as an expression.
case type varname
Where type is the name of the type to which the result of expr is to be converted, and varname is the object to which the result of expr is converted if the match succeeds.
- The case expression is true if any of the following is true:
- expr is an instance of the same type as type.
- expr is an instance of a type that derives from a type. In other words, the result of expr can be upcast to an instance of a type.
- expr has a compile-time type that is a base class of type, and expr has a runtime type that is type or is derived from type. The compile-time type of a variable is the variable's type as defined in its type declaration. The runtime type of a variable is the type of instance that is assigned to that variable.
- expr is an instance of a type that implements the type interface.
The following code example in Listing 7 uses a type to compare with an enum, an Array, and a List as an expression in the switch..case statement.
using System;
using System.Collections;
using System.Collections.Generic;
public class Author
{
string name;
string book;
int year;
public Author(string Name, string Book, int Year)
{
this.name = Name;
this.book = Book;
this.year = Year;
}
}
public enum Color { Red, Green, Blue, Black, Orange }
class SwitchCaseExample{
static void Main(string[] args)
{
// Pass an Enum
SwitchCaseWithTypePatternSample(Color.Red);
// Pass an Array
string[] names = {"Mahesh Chand", "Allen O'neill", "David McCarter"};
SwitchCaseWithTypePatternSample(names);
// Pass a List
List<Author> authors = new List<Author>();
authors.Add(new Author("Mahesh Chand", "ADO.NET Programming", 2002));
SwitchCaseWithTypePatternSample(authors);
Console.ReadKey();
}
public static void SwitchCaseWithTypePatternSample(object type)
{
switch (type)
{
case Enum e:
switch (e)
{
case Color.Red:
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Red");
break;
case Color.Green:
Console.BackgroundColor = ConsoleColor.Green;
Console.Clear();
Console.WriteLine("Green");
break;
case Color.Blue:
case Color.Black:
case Color.Orange:
default:
Console.WriteLine("No need to change background.");
break;
}
break;
case Array a:
Console.WriteLine($"Number of items in array: {a.Length}");
break;
case IList list:
Console.WriteLine($"Number of items in list: {list.Count}");
break;
default:
Console.WriteLine("default");
break;
}
}
Listing 7.
Summary
This article and code examples demonstrate various use cases of the C# switch..case statement.