Null Parameter Checking in C#

Null Reference Exception is one of the worst bugs that you can have in your code. It is just painful. In order to protect this type of exception, you can try this new feature which can help you to make your code more readable and robust.

Current Problem

At the moment, if you want to check a certain parameter of your function is null, you have to do something like this:


    
public SomeFunction(int id, SomeClass newObject)
{
if (newObject == null)
{
throw new ArgumentNullException("newObject");
}
...
}
    

C# 10 Feature

The new version of C# aims to simplify your problem with – !!. All you have to do is add two exclamation points after the name of the parameter.


    
public SomeFunction(int id, SomeClass newObject!!)
{
...
}
 

In this example, the code will automatically check if newObject is null. The ArgumentNullException will be automatically thrown if the newObject value is null.

Written by:

Ilyas Patel

    last updated 1 year ago