Why null in C# is so bad (2024)

Miguel Bernard

Posted on • Updated on • Originally published at blog.miguelbernard.com

Why null in C# is so bad (3) Why null in C# is so bad (4) Why null in C# is so bad (5) Why null in C# is so bad (6) Why null in C# is so bad (7)

#dotnet #csharp #aspnet #dotnetcore

In my career, more than half of the bugs I encountered were related in a way or another to a null value being propagated where it shouldn't have been—therefore resulting in unexpected behaviors or a nasty NullReferenceException.

Why is null such a problem in C#? Well... the null problem (a.k.a the billion-dollar mistake) breaks many assumptions you can make about the programming language.

In more theoretical terms, it breaks the Liskov substitution principle. (One of the famous SOLID principles)

Let Φ(x) be a property provable about objects x of type T. Then Φ(y)should be true for objects y of type S where S is a subtype of T.

Why null in C# is so bad (8)

Did I lose you? Great! Now let's talk plain English.

It means that you should be able to use any subtype in place of its parent type without affecting the behavior of the application.

What does that have to do with null?

In the C# compiler, there's a rule to enforce and prevent multiple inheritances... except... for null. Null is a special instruction in the language that can substitute any type. Put in another way; it means that null inherits from all reference types.

Because of that, you cannot think of your code logically anymore. You always have to check if the value is of subtype null or not. You have to check this because null behave in a very different way than any other type. It needs special processing and/or logic branching.

var customer = this._customerRepository.Get();if (customer != null){ // rest of the logic here.}else{ // logic for the null case here.}

This practice, often referenced as defensive programming, makes your code verbose and error-prone. It works fine-ishhh. To make it work, you need to do it everywhere in your system. It's really easy to forget one location and guess what? It's precisely where you're going to get a NullReferenceException popping up in production.

Yes, of course, you can use the more beautiful Elvis operator ?., but it doesn't solve anything. It just makes the code more readable.

The only real solution is to get rid of all the null. That being said, unless you have very strict coding rules within your team, I doubt you'll be able to do it. It's always tempting as a developer to take a shortcut and return a null value on a function call.

C# 8.0 to the rescue

Fortunately, C# 8.0 adds a brand new feature to help us with the null witch hunt. That new option instructs the compiler to check for null values in all code paths. Simply add this line to your .csproj and voilà!

<Nullable>enable</Nullable>

Why null in C# is so bad (9)

Then you can start getting rid of those null values and make sure nobody introduces new ones behind your back.

Using that will most likely break everything on a brownfield project, but for greenfield projects, I highly recommend you enable it. It might seem more work at first, but writing code without passing null around will save you many long, painful debugging hours in production. Ask me how I know. For me, that upfront development cost is a no-brainer.

Good hunt!

Top comments (14)

Subscribe

Zohar Peled

Zohar Peled

By day, try to work.By night, try to sleep.

  • Location

    Israel

  • Work

    .Net Developer

  • Joined

Apr 26 '20

  • Copy link

I've been programming for two decades now and have been working with .Net since 1.1 - and though admittedly most of the projects I've been working on was small ones, with either just a me as the single developer or a small team of up to four developers - I have to say that personally, I've never thought about null as such a problematic concept. I've had the occasional NullReferenceException here and there throughout my career, but it wasn't so often as I've heard other developers complaining about...
Personally, I think I would prefer to see syntactic sugar for defensive coding over non-nullable reference types - because while I agree defensive coding is cumbersome and somewhat of a pain to write (especially since you want to instantiate and throw the ArgumentNullException from the each method so you're forced to repeat yourself) - I still find the option of returning null from a method (like, if you didn't find what you're looking for in the database, for example) quite attractive and easy to handle. I know you can implement (or download a nuget) the Maybe Monad to avoid having to use null), but that seems to be a bit more cumbersome to work with.

Kelly Brown

Kelly Brown

C# game dev

  • Location

    USA

  • Work

    Software Engineer

  • Joined

Apr 27 '20

  • Copy link

I still find the option of returning null from a method (like, if you didn't find what you're looking for in the database, for example) quite attractive and easy to handle.

I don't think this is being contested by anyone. However, if a method returns a string, I have no choice but to read the documentation or source code to know whether null is a legal return value. The thing I like about nullable references is that string? makes it 100% clear that null can and will happen.

Christian Baer

Professional Software Developer, mainly in Java. Also a little bit of JavaScript, CSS, HTML, XML and nearly everything else needed in WebDev

  • Joined

Apr 28 '20

  • Copy link

Please do not return null because your query did not find anything.
Null is the absence of information. It's the abbreviation for "I don't know what happened". Please don't put meaning to it. Do not return null in any case. Throw exceptions, return error objects or whatever, but do not return null. Null is contains zero information and has no meaning.

Zohar Peled

Zohar Peled

By day, try to work.By night, try to sleep.

  • Location

    Israel

  • Work

    .Net Developer

  • Joined

Apr 28 '20 • Edited on Apr 28 • Edited

  • Copy link

I would never suggest throwing an exception if something wasn't found in the database. that's an entirely non-exceptional situation and throwing an exception because of that would be, IMHO, a perfect example of a vexing exception.
(Even if you store information in a database that is needed for the software to run, such as configuration information - even in this case, I would rather handling the lack of critical information in code, rather then throwing an exception).

Also, Null in c# (like Nothing in Vb.Net) is not "the absence of information" - it's a reference that doesn't point to an instance. What you are referring to might be Null in the world of relational databases, where it is most accurately described as an unknown value.

To me, having a method returning null when data wasn't found makes perfect sense - because the data was not found, an instance of the return type could not have been initialized, and therefor you get back null.

This can be replaced by using something like the Maybe Monad (click here for a long but good explanation), but IMHO that's a more complicated solution to the same problem.
I mean, you'd have to check if the Maybe is none or if it contains a value anyway, so you might as well check if the reference is null - with no extra complication to your codebase.

Christian Baer

Christian Baer

Professional Software Developer, mainly in Java. Also a little bit of JavaScript, CSS, HTML, XML and nearly everything else needed in WebDev

  • Joined

Apr 28 '20

  • Copy link

A Reference that points to nothing is the absence of information. There is literally nothing (read: no information) behind the pointer.
For a database query neither null/Null nor an exception are the right tool. An empty List would be. If you query for exactly one Object (like with the id), null/Null can be an option. So could an Exception, as if you have an ID, there better be an object for this. This depends on the context.
Problem is: Null/null returns are also often misused. It is still dangerous and clutters code. For me it is a 'Do not use lightly'. I have to have a reason for using something so dangerous.

Zohar Peled

Zohar Peled

By day, try to work.By night, try to sleep.

  • Location

    Israel

  • Work

    .Net Developer

  • Joined

Apr 28 '20

  • Copy link

True, if you're selecting a list of object, an empty list (or an IEnumerable) would be the obvious choice of what to return when you find nothing that matches the search criteria. For a search of a single object, I see no problem with null. I guess we can simply agree to disagree.

Miguel Bernard

Miguel Bernard

Miguel has over 10 years of experience with Microsoft Technologies. Specialized with many things in the Microsoft ecosystem, including C#, F#, and Azure

  • Email

    mig@miguelbernard.com

  • Location

    Montreal, QC, CA

  • Work

    Director of Engineering at Nexus Innovations

  • Joined

Apr 27 '20

  • Copy link

I use Language-ext (github.com/louthy/language-ext) in all my projects now. It has made our code more readable and less error-prone using Either and Option in all our method's signatures. Doing so makes the returns very explicit for the caller instead of Exceptions and null which are implicit.

Option<int> -> Returns a int or not. e.g. GetById
Either<string, int> -> Returns a int in case of success and string in case of failure with the error message

Kelly Brown

Kelly Brown

C# game dev

  • Location

    USA

  • Work

    Software Engineer

  • Joined

Apr 27 '20

  • Copy link

Structs are a different story. Why would I use Option<int> when Nullable<int> (or int?) is an option? It clearly expresses that it may not return a value.

Evaldas Buinauskas

Evaldas Buinauskas

  • Location

    Lithuania

  • Education

    Bachelor of Computer Science

  • Work

    Search Engineer at Vinted

  • Joined

Apr 27 '20

  • Copy link

LanguageExt will force you to deal with null values, int? won't. Also lots of extension methods to deal with optional types.

Kelly Brown

Kelly Brown

C# game dev

  • Location

    USA

  • Work

    Software Engineer

  • Joined

Apr 27 '20

  • Copy link
<NullableReferenceTypes>true</NullableReferenceTypes>

I have not seen this tag before. Where did you find it? According to the docs, the tag is as follows:

<Nullable>enable</Nullable>

This is what I use.

Miguel Bernard

Miguel Bernard

Miguel has over 10 years of experience with Microsoft Technologies. Specialized with many things in the Microsoft ecosystem, including C#, F#, and Azure

  • Email

    mig@miguelbernard.com

  • Location

    Montreal, QC, CA

  • Work

    Director of Engineering at Nexus Innovations

  • Joined

Apr 27 '20

  • Copy link

You're right, they changed it between the preview release and the official release of C# 8.0. I'll update the post thank you for spotting it!

Frank Font

Frank Font

Technologist that knows people are more important.

  • Location

    USA

  • Work

    Holistic technologist at Various

  • Joined

Apr 26 '20 • Edited on Apr 26 • Edited

  • Copy link

Miguel, thanks for sharing this tip. Been a few years since I've done a C# project for a client but unexpected null values have always been a bane; and not just in C#.

Sometimes we want our programs to support capturing the fact we don't have a "real" value for a field. This does not violate SOLID. It does potentially double the cyclomatic complexity of our programs for each field where we want to support this.

Did Microsoft make a blunder (and Sun with Java and others) supporting null by default instead of as an option per class/object? I'm inclined to say yes. This should be an edge case because of the quality risk impact.

Nulls have their important use and should always be an option. But like salt, that option should be sprinkled in only where needed otherwise we might raise our blood pressure. :)

Tomas Fernandez

Tomas Fernandez

  • Joined

Apr 27 '20 • Edited on Apr 27 • Edited

  • Copy link

You can always use the Options pattern to avoid using a specific feature of a compiler and stop using null as return type.

ijossalex

ijossalex

  • Joined

Apr 1 '23

  • Copy link

The concept of "null" in C# can be problematic because it represents a lack of value or an absence of an object reference, which can lead to unexpected errors and exceptions in code.

One of the main issues with null in C# is the potential for NullReferenceException errors. This occurs when code attempts to access a null reference, which can cause the program to crash or behave unexpectedly. This is particularly problematic when working with large and complex applications, where it can be difficult to trace the source of the error.

Another issue with null in C# is that it can make code harder to read and understand. When a variable can be null, it requires extra checking and validation to ensure that it is not causing errors or unexpected behavior.

To address these issues, C# introduced the concept of nullable types, which allow variables to be explicitly declared as nullable or non-nullable. This helps to make code more robust and less prone to errors, by ensuring that null references are handled appropriately and that code is easier to understand and maintain. Source qsmart.qa/

For further actions, you may consider blocking this person and/or reporting abuse

Why null in C# is so bad (2024)
Top Articles
Where to Buy Property Without Paying Property Tax
The Twelve Claims for Taxes, updated for this pandemic holiday season
Sportsman Warehouse Cda
Cosentyx® 75 mg Injektionslösung in einer Fertigspritze - PatientenInfo-Service
41 annonces BMW Z3 occasion - ParuVendu.fr
3656 Curlew St
Sport Clip Hours
Seafood Bucket Cajun Style Seafood Restaurant in South Salt Lake - Restaurant menu and reviews
Viprow Golf
Tinker Repo
Teacup Yorkie For Sale Up To $400 In South Carolina
Eine Band wie ein Baum
Shopmonsterus Reviews
Blue Rain Lubbock
Diakimeko Leaks
2013 Ford Fusion Serpentine Belt Diagram
Ac-15 Gungeon
Craigslist Battle Ground Washington
Craigslist Maryland Trucks - By Owner
Black Panther 2 Showtimes Near Epic Theatres Of Palm Coast
Afni Collections
Motorcycle Blue Book Value Honda
Halsted Bus Tracker
Abga Gestation Calculator
Hoofdletters voor God in de NBV21 - Bijbelblog
Gasbuddy Lenoir Nc
Gideon Nicole Riddley Read Online Free
Barrage Enhancement Lost Ark
Blue Beetle Movie Tickets and Showtimes Near Me | Regal
Oreillys Federal And Evans
Vanessa West Tripod Jeffrey Dahmer
Domina Scarlett Ct
Skill Boss Guru
When His Eyes Opened Chapter 2048
Anya Banerjee Feet
Überblick zum Barotrauma - Überblick zum Barotrauma - MSD Manual Profi-Ausgabe
Electronic Music Duo Daft Punk Announces Split After Nearly 3 Decades
Craigslist en Santa Cruz, California: Tu Guía Definitiva para Comprar, Vender e Intercambiar - First Republic Craigslist
Ig Weekend Dow
How Much Is 10000 Nickels
Lucifer Morningstar Wiki
Enr 2100
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
Neil Young - Sugar Mountain (2008) - MusicMeter.nl
Adams-Buggs Funeral Services Obituaries
City Of Irving Tx Jail In-Custody List
Secrets Exposed: How to Test for Mold Exposure in Your Blood!
Lebron James Name Soundalikes
Congruent Triangles Coloring Activity Dinosaur Answer Key
Abigail Cordova Murder
Mawal Gameroom Download
WHAT WE CAN DO | Arizona Tile
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 5479

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.