We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.
Is there a reason why \"null\" has even been included in the l
Whether these are cases of use or abuse is subjective, but I use them sometimes.
Null in C# is mostly a carry-over from C++, which had pointers that didn't point to anything in memory (or rather, adress 0x00
). In this interview, Anders Hejlsberg says that he would've like to have added non-nullable reference types in C#.
Null also has a legitimate place in a type system, however, as something akin to the bottom type (where object
is the top type). In lisp, the bottom type is NIL
and in Scala it is Nothing
.
It would've been possible to design C# without any nulls but then you'd have to come up with an acceptable solution for the usages that people usually have for null
, such as unitialized-value
, not-found
, default-value
, undefined-value
, and None<T>
. There would've probably been less adoption amongst C++ and Java programmers if they did succeed in that anyhow. At least until they saw that C# programs never had any null pointer exceptions.
If you create an object with an instance variable being a reference to some object, what value would you suggest has this variable before you assigned any object reference to it?
Removing null wouldn't solve much. You would need to have a default reference for most variables that is set on init. Instead of null-reference exceptions you would get unexpected behaviour because the variable is pointing to the wrong objects. At least null-references fail fast instead of causing unexpected behaviour.
You can look at the null-object pattern for a way to solve part of this problem
Commonly - NullReferenceException means that some method didn't like what it was handed and returned a null reference, which was later used without checking the reference before use.
That method could have thown some more detailed exception instead of returning null, which complies with the fail fast mode of thinking.
Or the method might be returning null as a convenience to you, so that you can write if instead of try and avoid the "overhead" of an exception.
"Null" is included in the language because we have value types and reference types. It's probably a side effect, but a good one I think. It gives us a lot of power over how we manage memory effectively.
Why we have null? ...
Value types are stored on the "stack", their value sits directly in that piece of memory (i.e. int x = 5 means that that the memory location for that variable contains "5").
Reference types on the other hand have a "pointer" on the stack pointing to the actual value on the heap (i.e. string x = "ello" means that the memory block on the stack only contains an address pointing to the actual value on the heap).
A null value simply means that our value on the stack does not point to any actual value on the heap - it's an empty pointer.
Hope I explained that well enough.