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

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.

Latest comments (0)

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.