DEV Community

Tommy Williams
Tommy Williams

Posted on

How I misrepresented a C# 9 code feature

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:

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) { ... }
Enter fullscreen mode Exit fullscreen mode

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) { ... }
Enter fullscreen mode Exit fullscreen mode

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)