Wednesday, May 20, 2020

C# 9.0: Pattern Matching Improvements

At the Microsoft Build today, an early glimpse of C# 9.0 was announced. While C# 9.0 is officially to be announced in November, 2020 during dotnetconf, some of the features have already found their way out with Visual Studio Version 16.7.0 Preview 1.0. Some of those features are improvements to Pattern Matching which was/is a trending topic in C# 7.2 and 8.

With C# 9, we have access to type patterns, relational patterns and logical patterns. Let's have a look at what these are.

Consider I have a base class Customer, and two derived classes WalkInCustomer and OnlineCustomer. And I have the following method to get the discount percentage based on the Customer written using C# 9.0.
public double GetDiscountPercentage(Customer customer)
{
    return customer switch
    {
        WalkInCustomer => 0.2,
        OnlineCustomer onlineCustomer => onlineCustomer.Age switch
        {
            >= 60 and < 70 => 0.4,
            >= 70 => 0.6,
            _ => 0.3,
        },
        not null => throw new ArgumentException(nameof(customer)),
        null => throw new ArgumentNullException(nameof(customer))
    };
}
Here in the outer switch statement, I am using type pattern and logical (and, or, not) patterns. If the customer is not of type WalkInCustomer and OnlineCustomer, then I am throwing an exception. If the Customer is WalkInCustomer, giving a straight off discount of 20%. Then if the customer in an OnlineCustomer, based on the customers' age I am giving different discounts. Here to match the age, relational pattern along with logical pattern is used.

Isn't this nice!

On a last note, make sure you are using Visual Studio Version 16.7.0 Preview 1.0 and LangVersion is set to preview in your csproj file to try out early C# 9.0. And you can also check out https://sharplab.io/ and play around with other features that are still finding their way out!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment