Using a custom argument validation helper breaks code analysis
Asked Answered
A

1

12

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?

Agamic answered 16/5, 2017 at 15:16 Comment(5)
@DipenShah Very easily. Try it: try { string s = null; s.ThrowIfNull("s"); } catch (Exception ex) {/* set breakpoint here */ }Hormonal
What kind of code analysys? There are many.Jahnke
@Ed Plunkett interesting, good too know!Nikolas
This kind of "standard" CA: msdn.microsoft.com/library/ms182182.aspxBentwood
Show the method that causes the CA1062 or a simplified versionYnez
J
13

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.

Jahnke answered 16/5, 2017 at 15:42 Comment(6)
Thank you, I hoped that there's a technique like this, as for example ReSharper uses a similar kind of annotation to make such a helper work. I'll try this tomorrow and accept your answer.Bentwood
Yes, it works but pity it's not documented anywhere, or at least I didn't found (unlike Resharper attributes).Jahnke
I can't get this to work if I'm sharing this among many projects. I can only get this to work in a project if the project itself contains and defines this extension method. Any ideas?Wende
In particular, Sonarqube supports [ValidatedNotNull] (proof: github.com/SonarSource/sonar-dotnet/issues/5973 )Atrip
Just out of curiosity, does anyone know why this works in getting rid of the null warnings?Valance
@ManuelGuillen with this attribute you specifically say that you (as developer) validated this parameter cannot be null. So whole purpose of this attribute is to make that warning go away.Jahnke

© 2022 - 2024 — McMap. All rights reserved.