Breaking

Tuesday, May 4, 2021

C# 9 Switch Expressions with Type patterns

C# 9 allows you to combine the power of pattern matching with switch expressions.

I had a use case where I had to check the type of an object and depending on the type execute different logic.

Before C# 7 type checks where not possible, so although I wanted to write the following switch statement, this would not compile:

In C#7 Type pattern support was added so then I could write the following

C#9 further improves this by the introduction of switch expressions. Now I could handle this use case like this:

Neat!

No comments:

Post a Comment