FP S2302: nameof should not be used for 'just' words

Rule S2302 helps making use of the nameof() construct, which extremely powerful. It is also a rule that results in some noise now and then:

public static class Embedded
{
    public static (string Name, Stream Stream) Resolve(Assembly assembly, string name)
    {
        var fullName = $"{assembly.GetName().Name}.{name}";
        if (assembly.GetManifestResourceStream(fullName) is { } stream1)
        {
            return (Name: fullName, Stream: stream1);
        }
        else throw new FileNotFoundException($"Stream '{name}' not found in assembly {assembly}.", name); // Compliant, just a word in a sentence
    }
}

Interpolated strings like the on on in this snippet, are tricky, and I guess error prone. Please reconsider the evaluation of interpolated strings. I’m not sure what a good improvement should be, but I do know I see some FP’s on this rule in the codebases I work on.

Note: that this snippet has been simplified compared to the actual code
Reported by SonarAnalyzer.CSharp v10.22.0.136894

Hello @Corniel.

Indeed this is a false positive - however, in my opinion this is a case where the rule hits a limitation of static analysis.

I don’t see a way to fix this without using natural language processing to try to understand the context/semantics of the word or by creating a heuristic that will probably create more FPs or FNs that it might solve. Additionally, I think this particular FP does not worth the trade off of the resources versus gain.

Let me know what you think about this.

I’m in doubt as well. I think you should do some analysis on this rules based on your customers data, and check if you can draw any conclusions from the false positives.

I would not be surprised if the FP rate is high on interpolated strings with (multiple) spaces, which might be a good way to decide to skip, but the data might tell.

I’ll look into it once there’s more time - currently we have other priorities and we are pretty busy.
Thanks for the input.

1 Like