DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Tip: ArgumentNullException.ThrowIfNull

Let’s talk about the ArgumentNullException.ThrowIfNull method, introduced in C# 10, which simplifies null argument checking and automatically throws exceptions when needed. See the example in the code below.

using System;

public class Program
{
    public static void Main()
    {
        string name = null;

        // Checks and throws an ArgumentNullException if the argument is null
        ArgumentNullException.ThrowIfNull(name, nameof(name));

        Console.WriteLine($"Name: {name}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
With the ThrowIfNull method, you can simplify the process of checking arguments that shouldn’t be null. Instead of manually writing checks to throw exceptions, you can use this method, which throws an ArgumentNullException automatically if the argument is null. This improves the readability and conciseness of your code when dealing with parameters. In the example above, we show how to use ThrowIfNull to ensure that an argument is not null when calling a method.

Source code: GitHub

I hope this tip helps you simplify null checks in your code! Until next time.

Top comments (0)