Never null-check again in C#

Enis Necipoğlu
1 min readMay 8, 2020

--

Null-checks are most common and boring code-blocks. A simple null-check code:

Each parameter will be checked with if statement and throw ArgumentNullException one by one.

Photo by Moritz Kindler on Unsplash

— -

NotNullAttribute

There is an attribute which is [NotNull] from System.Diagnostics.CodeAnalysis. This doesn’t check anything at runtime. It only works with CodeAnalysis and raises warnings or errors at compile time NOT at runtime!

Custom Solution

Let’s get rid of if statements for null-checks. How to handle assignment of method parameter in csharp? The answer is ‘you can not!’. But you can use another way to handle assignment with implicit operator. Let’s create NotNull <T>class and define an implicit operator then we can handle assignments.

Now we can use NotNull object as method parameter

As you can see DoSomething() method has cleaner code then before. Also you can use NotNull class with any type:

--

--