How to ignore Sonar rule to specific line of code in C#?

24.3k Views Asked by At

I use SonarLint. I want the sonar test not to be performed for a specific line. I used // NOSONAR but it didn't work. Does not specify the error number.

SS

The error still appears in SonarLint when I use //NOSONAR. But in the main project (SonarQube) the error no longer appears.

3

There are 3 best solutions below

0
Peska On BEST ANSWER

This is Visual Studio suggestion, not SonarLint warning. Also, I believe NOSONAR is not supported in Visual Studio. You can either suppress in source:

#pragma warning disable IDE0017
<your code>
#pragma warning restore IDE0017

Or in suppression file:

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0017:Simplify object initialization", Justification = "<Pending>", Scope = "member", Target = "~M:<your class and your method>")]
0
Mustafa Özçetin On

Another way is to use SuppressMessageAttribute with methods or classes. It allows suppressing a warning in only certain parts of your project or file. For example, you can suppress a warning in a method or class scope:

[System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Style",
    "IDE0017:Simplify object initialization",
    Justification = "<Pending>")]
void SetName(string name)
{
    var person = new Person();
    person.Name = name;
}

or

[System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Style",
    "IDE0017:Simplify object initialization",
    Justification = "<Pending>")]
class MyClass
{
}
0
Shashank On

To suppress warning you have two options.

  1. #pragma warning disable. if you are not sure what pragma you should use, install SonarLint extension for your visual studio.
  2. //NOSONAR It does work, if it is running through SonarQube server extension. Example if you're code is running through SonarQube task under build pipeline.