DEV Community

Discussion on: Dealing with Nothing in C# - The Null Object Pattern

Collapse
 
slavius profile image
Slavius • Edited

AFAIK there are currently measures to deal with null issues in C#

They are:

Nullable types System.Nullable<T>

int? Id = null;

Default literal

int i = default;

Null coalescing operator

int currentUserId = getUserId() ?? -1;

Null conditional operator

var userObject = null;
try {
   ...
}
catch {
   ...
}
finally {
  userObject?.Dispose();
}
Collapse
 
rubberduck profile image
Christopher McClellan

Nullable value types introduced the concept of null where previously a value couldn’t be null. (It’s essentially an option type.) The rest of these were introduced as syntactic sugar to help us deal with the fact that null exists in the language. In upcoming versions of C# you will be able to opt into nullability. Soon, the default mode of operation in C# will be “things can’t be null”.

Thread Thread
 
slavius profile image
Slavius

The benefit comes when you use Resharper because you can utilize code annotation attributes ([CanBeNull], [NotNull], [ItemCanBeNull], [ItemNotNull])

Thread Thread
 
rubberduck profile image
Christopher McClellan

So that’s exactly what I think you’re missing here. In upcoming versions, you won’t need those annotations. Take some time to look into Nullable reference types.

Thread Thread
 
slavius profile image
Slavius

I think it's far from being ready. Especailly if it introduces breaking changes. Switching midsets is difficult and if you hide a feature behind a compiler switch it's not going to work.

By the way John Skeet found 2 bugs straight away...