Safe casting with is

/images/2018/06/Is_keyword_Pattern.png

Just a short post on some pattern matching in C# 7 that my coworker pointed out to make code cleaner and easier to read. I had looked at pattern matching but not really used it exept in a switch statement.

Constantly null checking

In C# programming we are always doing null checking which tends to clutter up the code and make it less readable.

Here is such an example of a verbose null-checking.

public class TheHitchhikersGuideToTheGalaxy {
    
    public void WithoutPatternMatching()
    {
        var useDeepThought = false;
        var answer =   CalculateTheAnswerToTheUltimateQuestion(useDeepThought);

        if (answer == null)
        {
            System.Console.WriteLine($"Sorry the answer could´t be calculated. Return value was null");
        }
        else
        {
            System.Console.WriteLine($"The answer is {answer}");
        }
        
    private int? CalculateTheAnswerToTheUltimateQuestion(bool useDeepThought)
    {
        if (useDeepThought)
            return 42;
        else
            return null;
    }
}   

See git for the example.

Can we make this code little more readable?

I think so (if you are using C# 7 and up).

Use the is keyword

    public void WithPatternPatternMatching()
    {
        var useDeepThought = false;
        if (CalculateTheAnswerToTheUltimateQuestion(useDeepThought) is int answer)
        {
            // we can use the answer parameter since it was an int and has a value.
            System.Console.WriteLine($"The answer is {answer}");
        }
        else 
        {
            // the method returned a null (that is not an int so we don't have access to answer (its just null))
            System.Console.WriteLine($"Sorry the answer could´t be calculated. Return value was null");
        }
    }

In the example above the flow of the code (at least the happy path) is much better since we just get the answer variable with assigned value which we can use or we deal with the null last where it is not in our way.

Here is an excellent article you should read if you want to know more about basic pattern matching in C# 7.0: C# 7: Is Operator Patterns - You won’t need ‘as’ as often

Nullable Reference Types?

And now we just wait for Nullable Reference Types in C# to make our lives even better. But that will probably wait until C# 8.

Latest Posts