#9 – C# Switch Case Statement

C# has two statements for branching code: the if statement and the switch statement. In this tutorial, you will learn the key points of the switch statement.

Concept

A switch statement includes one or more switch sections. Each switch section contains one or more case labels (either a case or default label) followed by one or more statements.

Switch execute the section based on the match expression and only at most one switch section will be executed.

Pattern Matching

In C# 6 and earlier, the match expression must be an expression that returns a value of the following types: char, string, bool, integral value (int or long), enum. Starting with C# 7.0, the match expression can be any non-null expression.

Each case statement defines a pattern that, its containing section will be executed if it matches the match expression. C# 6 and earlier version only support Constant Pattern, starting with C# 7.0 supports following patterns:

  • Constant Pattern
  • Type Pattern

Constant Pattern

The constant pattern tests whether the match expression equals a specified constant:

  • 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.

Sample:

using System;

Color color = (Color)(new Random().Next(0, 5));

switch (color)
{
    case Color.RED:
        Console.WriteLine("Color is RED");
        break;
    case Color.GREEN:
        Console.WriteLine("Color is GREEN");
        break;
    case Color.BLUE:
        Console.WriteLine("Color is BLUE");
        break;
    case Color.YELLOW:
    case Color.WHITE:
        Console.WriteLine("Color is YELLOW or WHITE");
        break;
    default:
        Console.WriteLine("Color is N/A");
        break;
}


public enum Color
{
    RED,
    GREEN,
    BLUE,
    YELLOW,
    WHITE
}

Type Pattern

The type pattern enables concise type evaluation and conversion. the syntax is:

case type varname
  • type is the name of the type to which the result of expr is to be converted
  • varname is the object to which the result of expr is converted if the match succeeds.
  • If the case expression is true, varname is definitely assigned and has local scope within the switch section only.
  • The compile-time type of expr may be a generic type parameter, starting with C# 7.1.
  • Note that null doesn’t match a type. To match a null, you use the following case label: case null:

Sample:

using System;
using System.Collections.Generic;
using System.Linq;

int[] arr = { 2, 4, 6, 8, 10 };
ShowVarTypeInformation(arr);

IList<int> oddNum = new List<int>() { 1,3,5,7,9,11};
ShowVarTypeInformation(oddNum);

IList<string> strlist = new List<string>() {"Hello", "World" };
ShowVarTypeInformation(strlist);

IList<string> noElement = null;
ShowVarTypeInformation(noElement);


void ShowVarTypeInformation(object testvar)
{
    switch (testvar)
    {
        case Array arr:
            Console.WriteLine($"An Array with {arr.Length} elements");
            break;
        case IEnumerable<int> intIE:
            Console.WriteLine($"An IEnumerable with {intIE.Count()} elements");
            break;
        case IList<string> strList:
            Console.WriteLine($"A string list with {strList.Count()}");
            break;
        case null:
            Console.WriteLine("It is null. do nothing");
            break;
        default:
            Console.WriteLine("deafult label case section");
            break;
    }
}

Output:

An Array with 5 elements
An IEnumerable with 6 elements
A string list with 2
It is null. do nothing

When Clause

when clause to specify an additional condition that must be satisfied for the case statement to evaluate to true. The when clause can be any expression that returns a Boolean value.

Sample:

using System;
using System.Collections.Generic;
using System.Linq;

IList<int> evenList  = new List<int>() { 2, 4, 6, 8, 10 };
GetheckEvenOrOddInfo(evenList);

IList<int> oddList = new List<int>() { 1,3,5,7,9,11};
GetheckEvenOrOddInfo(oddList);


void GetheckEvenOrOddInfo(object testvar)
{
    switch (testvar)
    {
        case List<int> list when list.All(x=> x % 2 != 0):
            Console.WriteLine($"An odd list");
            break;
        case List<int> list when list.All(x=> x % 2 == 0):
            Console.WriteLine($"An even list");
            break;
    }
}

Output:

An even list
An odd list

One Reply to “#9 – C# Switch Case Statement”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.