In this post I am looking into the internals of the
is not pattern, which is introduced in C# 9. This pattern allows the code to be more expressive. Assume to have a method with a type of an
object input parameter, which needs validation. The method may only work if the object is a 2 character long
string value. For example, we would like to validate that the
string is a two letter country code.
C# 9 allows
is not patterns. Using this pattern, we can express the above example with the following code:
using System; object o1 = "UK"; if (o1 is not string countryCode || countryCode.Length != 2) Console.WriteLine("Invalid country code"); else Console.WriteLine(countryCode);