Avoiding the NullReferenceException

Easily, by a landslide, the most common exception I’ve run into in C# is the NullReferenceException.  Second would be an InvalidOperationException.  But NullReferenceException wins as most occurred exception hands down.  This quick post shows how we can start avoiding the NullReferenceException.

I despise null.  I despise null checks. 

What if there was a way to get rid of null checks?  Luckily there is.

Last year I was at a talk by Reid Evans, Getting Started with Functional Programming in F#.   He touched on it and I’ve been using an implementation in C# ever since.

Option

an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions which may or may not return a meaningful value when they are applied.

Optional Library

For this example, I’m going to use the Optional package.  There are many similar type libraries available on NuGet, but this one is fairly feature rich and serves the purpose for my example.

NullReferenceException

So I’m going to walk through a trivial example of a ASP.NET Core application that is going to return some customer data.  The sample code below will throw a NullReferenceException when the incoming customerId is not found in our database.

Null Check

Obvious answer is to wrap the return statement in an if statement to verify the customer returned from the _customerRepository is not null.  If it is, then return a 404.

Option

Our CustomerRepository, could’ve thrown a InvalidOperationException or another type of exception if the customer didn’t exist.  But what if instead it returned an Option<Customer> and never returned null.

In the example below, our _customerRepository.GetOptionById(int) now returns an Option<Customer>. This now forces us to specify how to handle if there is a value, and if it is null.

Gateway

Hopefully this a a simple example of the Option type and how it can be a gateway to removing null and NullReferenceException from your code.  Take a deeper look at the docs for the Optional library as there are many other great examples.

Are you using an implementation of Option/Maybe?  Let me know in the comments or on Twitter.