loading...

Dealing with Nothing in C# - The Null Object Pattern

Botond Balázs on September 01, 2018

This is the English version of my original post in Hungarian. Photo by Samuel Zeller on Unsplash. The null reference is so ubiquitous, such an i... [Read Full]
markdown guide
 

The next version of C# will make huge strides toward making null a nonissue. Nullable reference types.

 

AFAIK there are currently measures to deal with null issues in C#

They are:

Nullable types System.Nullable<T>

int? Id = null;

Default literal

int i = default;

Null coalescing operator

int currentUserId = getUserId() ?? -1;

Null conditional operator

var userObject = null;
try {
   ...
}
catch {
   ...
}
finally {
  userObject?.Dispose();
}
 

Nullable value types introduced the concept of null where previously a value couldn’t be null. (It’s essentially an option type.) The rest of these were introduced as syntactic sugar to help us deal with the fact that null exists in the language. In upcoming versions of C# you will be able to opt into nullability. Soon, the default mode of operation in C# will be “things can’t be null”.

So that’s exactly what I think you’re missing here. In upcoming versions, you won’t need those annotations. Take some time to look into Nullable reference types.

I think it's far from being ready. Especailly if it introduces breaking changes. Switching midsets is difficult and if you hide a feature behind a compiler switch it's not going to work.

By the way John Skeet found 2 bugs straight away...

 

Awesome, I knew they were working on it but I didn't know they already have a working prototype I can download!

 

Very well written and straightforward - thanks!

Using the same pattern but in the context of collections, C# has ways to define "empty" collections. For example, a collection of IEnumerable can use the Null Object pattern this way:

IEnumerable<SomeModel> collection = Enumerable.Empty<SomeModel>();

Looking forward to the next article!

 

Interesting pattern - for a more general purpose solution to the null-safety issue when no default can be defined, I'd recommend the Maybe / Option pattern, which is a universally equivalent (but type-safe) alternative to null references

 

Very good overview of the null object pattern.
Others already mentioned Maybe/Optional pattern. Here's my take on that pattern: github.com/j2jensen/callmemaybe
I'm definitely looking forward to nullable reference types in C# 8!

 

Thank you Botond for providing a concrete example to make it easier to digest the Null Object pattern (NOP hereafter since it's too long to type 😉).

I've been using NOP happily and worked great when used in conjunction with Singleton Pattern (😱).

Shameless plug: I've touched on it briefly here.

 

You laid out the problem and then the solution very clearly. Thank you! Quite a satisfying read.

 
 

Well explained and easy to follow. Thank you!

 
 
 
code of conduct - report abuse