Yesterday, I complained about some of the new syntax in C# 9 and, in so doing, made the opposite point I intended. Let me explain.
First the tweet:
OK C# 9 fans.
How is this:
if (listOfThings is null or { Count: 0 }) { ... }
better than what we used to do?
if (listOfThings?.Count == 0) { ... }
I'm seeing that first pattern all over the place from the #dotnet team and don't see the value except to show off new features.19:07 PM - 12 Nov 2020
The big problem here is that my pre-C# 9 example doesn't do the same thing as the C# 9 code.
To get the same behavior, I needed to write this:
if (listOfThings is null || listOfThings.Count == 0) { ... }
You can see a running example with various types of checks at https://dotnetfiddle.net/VNO2Sv
What I got wrong
I was so focused on the Count part that I forgot about the null check part. The C# 9 example makes that very clear.
And in my .NET Fiddle example, you can see that the syntax I was using doesn't work at all if you are instead checking for an enumerable with items in it when the List is null:
listOfThings = null;
if (listOfThings?.Count != 0) { ... }
That will give you a false positive (indeed, .Count
on a null object is not equal to 0) but then you'll have a NullReferenceException if you try to operate on listOfThings
in the if block.
Just a little reminder that the language designers aren't just making changes for the heck of it.
Top comments (0)