.NET 6 introduces a new helper class that uses the new [CallerArgumentExpression] attribute and the [DoesNotReturn] attribute; the ArgumentNullException helper class.
This class gives you an easy-to-use helper class that throws an ArgumentNullException for null values.
Thanks to the [CallerArgumentExpression] attribute this helper method gives you better error messages as it can capture the expressions passed to a method.
This is the implementation of this helper class:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArgumentNullException | |
{ | |
public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) | |
{ | |
if (argument is null) | |
{ | |
Throw(paramName); | |
} | |
} | |
[DoesNotReturn] | |
private static void Throw(string? paramName) => | |
throw new ArgumentNullException(paramName); | |
} |
Before C# 10, you probably would have used the nameof keyword and implemented this helper class like this:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArgumentNullException | |
{ | |
public static void ThrowIfNull([NotNull] object? argument) | |
{ | |
if (argument is null) | |
{ | |
throw new ArgumentNullException(nameof(argument)); | |
} | |
} | |
} |