The C# language contains really nice and useful features that are not so common to see across the projects we normally work on. One of these examples is the use of “when” keyword as an additional way to filter conditions. It helps us to have a cleaner and readable code in certain scenarios.
Currently, it is possible to use “when” in two cases: switch and catch statements.
The following example represents a code using the “when” filter for switch statement:
In the cases where a routine could have multiple conditions and possibilities, it is much better to use the switch/case statement instead of several multiple if/else clauses. It makes the code more readable and you can combine extra conditions using the when contextual keyword.
This is a more common use of when the keyword in C# since it is available since the C# 6.0. In try/catch clauses, the catch block is executed if the thrown exception is exactly the same type as the one specified in the catch parameter. But, what about if we want to make extra conditions on that, such as error number?
As you can see in the following code sample, it is possible to make conditions in catch clauses:
In this example, in case there is an exception in the doc conversion attempt, there is an intention of checking if the problem was caused by the expired license of an external library by verifying if the exception contains the word “License” and the number “2001” on it is message property. It is much better than create if statements inside the catch clause.
The Tech Platform