All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S2302.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Because parameter names could be changed during refactoring, they should not be spelled out literally in strings. Instead, use nameof(), and the string that’s output will always be correct.

This rule raises an issue when a string in the throw statement contains the name of one of the method parameters.

Noncompliant code example

void DoSomething(int someParameter, string anotherParam)
{
    if (someParameter < 0)
    {
        throw new ArgumentException("Bad argument", "someParameter");  // Noncompliant
    }
    if (anotherParam == null)
    {
        throw new Exception("anotherParam should not be null"); // Noncompliant
    }
}

Compliant solution

void DoSomething(int someParameter)
{
    if (someParameter < 0)
    {
        throw new ArgumentException("Bad argument", nameof(someParameter));
    }
    if (anotherParam == null)
    {
        throw new Exception($"{nameof(anotherParam)} should not be null");
    }
}

Exceptions

  • The rule doesn’t raise any issue when using C# < 6.0.
  • When the parameter name is contained in a sentence inside the throw statement string, the rule will raise an issue only if the parameter name is at least 5 characters long. This is to avoid false positives.




© 2015 - 2024 Weber Informatics LLC | Privacy Policy