Null pointers have been described as the "billion dollar mistake". Some languages have reference types which can't be assigned the null value.
I wonder if in designing a new object-oriented language whether the default behavior should be for references to prevent being assigned null. A special version of the could then be used to override this behavior. For example:
MyClass notNullable = new MyClass();
notNullable = null; // Error!
// a la C#, where "T?" means "Nullable<T>"
MyClass? nullable = new MyClass();
nullable = null; // Allowed
So my question is, is there any reason not to do this in a new programming language?
EDIT:
I wanted to add that a recent comment on my blog pointed out that non-nullable types have a particular problem whenb used in Arrays. I also want to thank everyone for their useful insights. It is very helpful, sorry I could only choose one answer.
The biggest "null-related mistake" in language design is the lack of a trap when indexing null pointers. Many compiler will trap when trying to dereference a null pointer will not trap if one adds an offset to a pointer and tries to dereference that. In the C standard, trying to add the offset is Undefined Behavior, and the performance cost of checking the pointer there would be no worse than checking the dereference (especially if the compiler could realize that if it checked that the pointer was non-null before adding the offset, it might not need to re-check afterward).
As for language support for non-nullable variables, it may be useful to have a means of requesting that certain variables or fields whose declarations include an initial value should automatically test any writes to ensure that an immediate exception will occur if an attempt is made to write null to them. Arrays could include a similar feature, if there were an efficient idiomatic way of constructing an array by constructing all the elements and not making the array object itself available before construction was complete. Note that there should probably also be a way of specifying a cleanup function to be called on all previously-constructed elements if an exception occurs before all elements have been constructed.
Finally, it would be helpful if one could specify that certain instance members should be invoked with non-virtual calls, and should be invokable even on null items. Something like
String.IsNullOrEmpty(someStringVariable)
is hideous compared withsomeStringVariable.IsNullOrEmpty
.