.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:
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:
public class ArgumentNullException | |
{ | |
public static void ThrowIfNull([NotNull] object? argument) | |
{ | |
if (argument is null) | |
{ | |
throw new ArgumentNullException(nameof(argument)); | |
} | |
} | |
} |
No comments:
Post a Comment