Jump to content

Conditional Cases in Switch Statements

From Knowledge Base

When working with switch statements, you can use a when clause instead of an if/else in your case expressions. The switch statement with pattern matching was introduced in C# 7.

switch( cow.Name )
{
    case "Alf":
        if( cow.Weight >= 100 )
        {
            // Do This
        } 
        else
        {
            // Do that
        }
        break;
    default:
        // Else
        break;
}
switch ( cow.Name )
{
    case "Alf" when cow.Weight >= 100 :
        // Do this
        break;
    case "Alf":
        // Do that
        break;
    default:
        // Else
        break;
}

Order is important when replacing if/else inside cases with when clauses. The case/when should be higher than the corresponding case without when.