Champions of C# 9 : “Simplified parameter null validation code”

In this blog post I wan’t to have a closer look at a current proposals for the upcoming C# Version 9.

Proposal #2145 – Simplified parameter null validation code.

Usually, if handing over parameters to a method, some checking for NULL is required to prevent unexpected behavior. Have a look at the following sample of a method with some checking.

private string ParseText(string text)
{
    if (text is null)
    {
      throw new ArgumentException(nameof(text));
    }
    return text;
}

In C# 9, this code could be simplified by adding ! as an indicator for “Will not be NULL” to the parametername. The code would then look like this.

private string ParseText(string text!)
{
    return text;
}

Based on This discussion from summer 2019, the new syntax is supposed to throw an Exception too, if the constraint is violated. Most likely also an ArgumentException, but this doesn’t seem to have specified yet.