C# is not
TL;DR
if (myVar is not null) DoSomething();
New C# 9 keyword: not
One of the smaller (less headline grabbing) additions to C# 9 is pattern matching (enhancements). And one of the smaller, but probably one of the features that will be most used, is the ‘not’ keyword.
Previously a common ‘not null’ check would be:
// no longer recommended as equals operator can be over-ridden
if (myVar != null) DoSomething();
// hard to read
if (!(myVar is null)) DoSomething();
C# 9 version:
if (myVar is not null) DoSomething();
The not keyword is part of the enhanced pattern matching.
Refs:
- https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements
- https://www.infoq.com/news/2020/07/CSharp-And-Or-Not/
Read other posts