Null Parameter Checking : An interesting way



we can write the code for a null check as below

string? name = null;
CheckName(name);
void CheckName(string name)
{
    if(name is null)
    {
        throw new ArgumentNullException(nameof(name));
    }
    Console.WriteLine(name);
}

//We can replace the if condition with the below one-liner code:

void CheckName(string name)
{
    //if(name is null)
    //{
    //    throw new ArgumentNullException(nameof(name));
    //}
    ArgumentNullException.ThrowIfNull(name);
    Console.WriteLine(name);
}

0 Comment's

Comment Form

Submit Comment