I'd like to use a custom helper to simplify argument validation, something like this.
public static void ThrowIfNull(this object value, string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
}
However, the static code analysis of course doesn't know that I do validate the input in public methods when using this helper, so it gives me CA1062
errors about public method arguments not being validated.
The particular issue is this one.
Is there a way to teach the code analyzer that this helper handles argument null validation? What is the proper solution for this issue?
Create attribute with the following name:
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class ValidatedNotNullAttribute : Attribute {}
Then apply it to the argument you are validating:
public static void ThrowIfNull([ValidatedNotNull] this object value, string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
}
And the warning should go away.
You can see this attribute is used by many libraries, including .net framework itself, for example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With