C# Language Keywords when

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


The when is a keyword added in C# 6, and it is used for exception filtering.

Before the introduction of the when keyword, you could have had one catch clause for each type of exception; with the addition of the keyword, a more fine-grained control is now possible.

A when expression is attached to a catch branch, and only if the when condition is true, the catch clause will be executed. It is possible to have several catch clauses with the same exception class types, and different when conditions.

private void CatchException(Action action)
    // exception filter
    catch (Exception ex) when (ex.Message.Contains("when"))
        Console.WriteLine("Caught an exception with when");

    catch (Exception ex)
        Console.WriteLine("Caught an exception without when");

private void Method1() { throw new Exception("message for exception with when"); }
private void Method2() { throw new Exception("message for general exception"); }


Got any C# Language Question?