#10 – C# Switch Expression

In this tutorial, you will learn the key point of C# switch expression for writing more cleaner code.

Beginning with C# 8.0, you can use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression. 

Switch Expression is not the same with Switch Statement. Following is the code example of switch statement:

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


var memberOne = new Member() 
{
    cardNo = "100011",
    Points = 300,
};
var memberTwo = new Member() 
{
    cardNo = "100012",
    Points = 8000,
};

Console.WriteLine($"MemberOne's tier is: {GetTierOfMember(memberOne)}");
Console.WriteLine($"MemberTwo's tier is: {GetTierOfMember(memberTwo)}");

string GetTierOfMember(Member mem)
{
    string tier = "BRONZE";

    switch (mem)
    {
        case Member m when m.Points > 10000:
            tier = "BLACK";
            break;
        case Member m when m.Points > 5000:
            tier = "GOLD";
            break;
        case Member m when m.Points > 1000:
            tier = "SILVER";
            break;
    }

    return tier;
}


class Member
{
    public string cardNo { get; set; }
    public int Points{ get; set; }
}

Rewrite the GetTierOfMember method with switch expression, the code are much more cleaner as following:

string GetTierOfMember(Member mem)
{
    string tier = mem.Points switch
    {
        > 10000 => "BLACK",
        > 5000 => "GOLD",
        > 1000 => "SILVER",
        _ => "BRONZE"
    };

    return tier;
}

In case the object is null, you can refactor above code with property patterns as following:

string GetTierOfMember(Member mem)
{
    string tier = mem switch
    {
        {Points: > 10000 } => "BLACK",
        {Points: > 5000 } => "GOLD",
        {Points: > 1000 } => "SILVER",
        _ => "BRONZE"

    };

    return tier;
}

Summary

In this tutorial, you have learned that how to write more cleaner code with C# switch expression instead of switch 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.