DEV Community

Cover image for Why null in C# is so bad

Why null in C# is so bad

Miguel Bernard on April 26, 2020

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 be...
Collapse
 
peledzohar profile image
Zohar Peled

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.

Collapse
 
thebuzzsaw profile image
Kelly Brown

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.

Collapse
 
donut87 profile image
Christian Baer

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.

Collapse
 
peledzohar profile image
Zohar Peled • Edited

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.

Thread Thread
 
donut87 profile image
Christian Baer

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.

Thread Thread
 
peledzohar profile image
Zohar Peled

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.

Collapse
 
mbernard profile image
Miguel Bernard

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

Collapse
 
thebuzzsaw profile image
Kelly Brown

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.

Collapse
 
buinauskas profile image
Evaldas Buinauskas

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

Collapse
 
thebuzzsaw profile image
Kelly Brown
<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.

Collapse
 
mbernard profile image
Miguel Bernard

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!

Collapse
 
frankfont profile image
Frank Font • Edited

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. :)

Collapse
 
tomsfernandez profile image
Tomas Fernandez • Edited

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

Collapse
 
ijossalex profile image
ijossalex

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/