Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom argument validation helper breaks code analysis

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?

like image 409
Zoltán Tamási Avatar asked May 16 '17 15:05

Zoltán Tamási


1 Answers

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.

like image 78
Evk Avatar answered Sep 21 '22 03:09

Evk