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.

Oldest comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.