Visual Studio | Using SonarLint | Rules and languages

Was this page helpful?

On this page

Install Free

Rules and languages

The Sonar Rules catalog is the entry point where you can discover all the existing rules. While running an analysis, SonarLint raises an issue every time a piece of code breaks a coding rule. 

Issues in your code are linked to Clean Code code attributes. When an issue is detected, it signifies that this part of your code is not consistent, intentional, adaptable, or responsible enough and that it impacts one or multiple software qualities. 

For more information about Clean Code attributes and software qualities, check out the Clean Code introduction page.

Overview

When opening a project containing C#, VB, C++, JS or TS files, SonarLint for Visual Studio will check your code against the following rules:

In addition, you will benefit from the following code analyzers: Sonar C#Sonar VB.NetSonar C-Family for C or C++, and SonarJS.

For C# and VB.Net, new issues will be reported as you type. You do not have to select Run Code Analysis from the Analyze menu - the rules are run automatically. Note that by default, Visual Studio is configured to only run Roslyn analyzers on files that are currently open. You can choose to have the analysis run on the entire solution as described in the Microsoft docs, although this is obviously more processor-intensive.

For C, C++, JavaScript, and TypeScript, new issues will be reported when you open or save a file. Issues are highlighted in your code, and also listed in the 'Error List'.

You can access the detailed rule description directly from the issue in the Error List, using the Show Error help option on the contextual menu.

See the page on Connected Mode for more details about language support for analyses while connected to SonarQube or SonarCloud.  

Rule selection

The rules can be enabled and disabled locally. It is not currently possible to suppress individual issues. If you are using Connected Mode with SonarQube or SonarCloud, the rule severities defined in the Quality Profile will be used.

Language-specific configuration

Define C# or VB.NET rules for local analysis

The Sonar C# and Sonar VB rules are implemented as Roslyn VSIX analyzers, and you can configure which rules are executed using the normal ruleset mechanism in VS.

How can I configure the C#/VB.NET rules to use?

SonarLint itself does not have any special behavior in relation to configuring the set of Sonar C#/VB.NET rules. The Sonar C# and VB.NET rules are implemented as Roslyn analyzers and use the standard Visual Studio features to enable and disable rules.

For VS2015 and VS2017 this means ruleset files. VS2019+ users can use .editorconfig files instead.

The simplest approach is just to reference the ruleset directly from the project and check the ruleset file in to source control. This won't have any adverse impact on machines that don't have SonarLint installed; Visual Studio will load the ruleset file, but it won't have any impact on build or in the IDE because the analyzers are not available.

How can I configure the C#/VB.NET rules to use without changing the project file or checking files in to source control?

There are a number of ways to achieve this, depending on the version of VS you are using. Some of the possible solutions are listed below. There may be others - see the Microsoft documentation Customize your build for more ideas.

1) Configure the rules in a .editorconfig file that is not under source control

The Visual Studio will search up the directory tree from the solution folder to locate a .editorconfig file. Create a .editorconfig file containing the required settings and drop it in a folder above the solution that is not under source control. See Set rule severity in an EditorConfig file in the Microsoft documentation for more information (setting a severity to "none" will disable a rule).

Limitations:

  • this will only work in VS2019 or later
  • it won't work if your solution already references a .editorconfig file

2) Add a Directory.Build.props file that references the ruleset file

The Directory.Build.props file will automatically be imported by MSBuild (and by extension Visual Studio). The file can be in the project directory or any parent directory so it should be possible to put it in a folder above the project/solution that is not under source code control.

Example:

<!-- Sample Directory.Build.props content -->
<Project>
  <PropertyGroup>
    <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Example.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
</Project>

Limitations:

  • this will only work on VS2017 or later.
  • it won't work if your solution has a Directory.Build.props file checked in.
  • it won't work if your solution already references a ruleset file.

3) Conditionally reference the ruleset file from the project, but don't check the ruleset file in to source control. The ruleset can be placed anywhere on your machine.

Example:

<!-- Snippet to conditionally set the ruleset to file that might not exist on all dev machines -->
<PropertyGroup>
  <CodeAnalysisRuleset Condition="Exists('$(LocalAppData)\Example.ruleset')">$(LocalAppData)\Example.ruleset</CodeAnalysisRuleset>
</PropertyGroup>

Limitations:

  • this does involve changing the project file(s), but only to add a single property.

4) Drop a props file that imports the ruleset file into the MSBuild ImportBefore folders

Project files that use the standard Microsoft build targets will automatically import any targets files that are exist in a well-known location. You can use this feature to conditionally import a ruleset.

This is similar to option (2) above but works with all versions of MSBuild.

Example:

<?xml version="1.0" encoding="utf-8"?>
<!-- Example props file to drop in %LocalAppData%\Microsoft\MSBuild\[VERSION]\Microsoft.Common.targets\ImportBefore -->
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <CodeAnalysisRuleset Condition="Exists('$(LocalAppData)\Example.ruleset')">$(LocalAppData)\Example.ruleset</CodeAnalysisRuleset>
  </PropertyGroup>
</Project>

Notes:

  • the location of the ImportBefore folder varies depending on the version of MSBuild, based on the following standard pattern: %LocalAppData%\Microsoft\MSBuild\[VERSION]\Microsoft.Common.targets\ImportBefore. The [VERSION] values for MSBuild 14 and 15 are 14.0 and 15.0 respectively. MSBuild 16 and latter use Current.
  • the ImportBefore folder does not exist by default so you might have to create it.

Limitations:

  • it won't work if your project already references a ruleset file.
  • the location of the ImportBefore folder varies according to the version of MSBuild, so if you are using multiple versions of Visual Studio you will need to drop the same file in multiple locations.
Define C, C++, JS, TS or secrets detection rules for local analysis

In standalone mode, it is possible to enable or disable rules, configure rule parameters, and in versions 4.13-7.2, change the reported rule severity. Not all options are supported for all languages. See the table below for more information:

LanguageFrom versionEnable/disableChange severityConfigure rule parameters
C4.13SupportedSupported in v4.13-7.2Supported
C++4.13SupportedSupported in v4.13-7.2Supported
JavaScript4.35SupportedNot supported. See #2399.Not supported. See #2400.
TypeScript4.35SupportedNot supported. See #2399.Not supported. See #2400.
Secrets detection6.4SupportedNot SupportedNot applicable

Disabling a rule

To disable a rule, select an instance of the rule in the Error List and select the Disable SonarLint rule command on the context menu:

SonarLint rules can be disabled directly in the IDE.

You can view and change the current rule settings by selecting Edit rules settings from the SonarLint > Tools > Options page:

It is possible to edit the SonarLint rule settings directly in the IDE.

When the rule settings are changed (either by using the Disable SonarLint rule command or by directly editing and saving the settings.json file), SonarLint will automatically re-analyze all open documents.

The SonarLint Output window tab contains text output describing the processing that has taken place; see this example:

The SonarLint output window will give you the analysis logs in more detail.

settings.json file format and location

The settings.json file is stored in user's roaming profile %APPDATA%\SonarLint for Visual Studio. It applies to all supported versions of Visual Studio. If the machine is domain-joined, then the settings file will be automatically copied to any other machine in the domain that the user logs on to.

The format of the settings file is as follows:

The format of the rule key in the file is [c|cpp|javascript|typescript]:[rule id]. The full list of rules is available at https://rules.sonarsource.com/.

Valid severity values are BlockerCriticalMajorMinor and Info. Changing the severity of a rule only affects the label in the Category column in the Error List.

If the settings file does not contain an entry for a rule then the default setting for the rule in the SonarWay Quality Profile will be used.

Note: if the solution is in Connected Mode then the settings file is ignored. Connected Mode is not currently for JavaScript or TypeScript - see #770. It is also not available for Secrets detection rules, which are only run in the IDE and so cannot be configured on the server.

Sonar Rule Descriptions

From SonarLint for Visual Studio v6.14+, users are able to visualize descriptive and educational content associated with each issue. Simply select the issue’s rule as shown below to open the Sonar Rule Help view to view the rule descriptions.

The SonarLint Rule Help view will give you lots of information to help you fix your issue.

The Sonar Rule Help view brings rule descriptions and patch instructions relevant to the library or framework you’re using, directly into the IDE. The rule descriptions include a brief explanation of the rule as well as Noncompliant and Compliant code samples.

Users are able to visualize a diff view for the non & compliant code samples which should help you fix your issue. Note that diff highlighting is only available for rules descriptions migrated to the new format, and we're progressively migrating all existing rules to the new format.

SonarLint will give you a noncompliant (in red) and compliant (in green) code sample when available.

An issue’s Clean Code attribute, software qualities, and severity are presented to you when opening the Sonar Rule Help view. Below the rule title, you will find the Clean Code issue badges that highlight an issue’s Clean Code classification. 

Clean Code attributes and software qualities as they appear in the SonarLint Rule Help view window.

Check the Clean Code definition page for details about Clean Code attributes, and the Clean Code benefits page to better understand software qualities for more details about how they help classify your issue. 

Be sure to check out the Investigating issues page for more details about how issues appear in your IDE.

Applying rules while in Connected Mode

Connected Mode syncs your SonarQube or SonarCloud Quality Profile with the local analysis to suppress issues reported in the IDE. See the Connected Mode documentation for more information.

Rule severities

The Sonar rule severities defined by SonarQube and SonarCloud are different than the severities defined by Visual Studio. The mapping from Sonar severities to Visual Studio severities are as follows:

SonarQube/SonarCloudVisual Studio
LowMessage
MediumWarning
HighWarning

If you are using Connected Mode, the rule severities defined in the Quality Profile will be used.

Secrets detection

Starting with v6.4, SonarLint for Visual Studio will detect and report hard-coded cloud secrets as issues.

Secrets detection is now possible in SonarLint for Visual Studio.

All types of text files are analysed, irrespective of the type of content (code, configuration, documentation etc). Analysis is triggered whenever a text file is opened or saved.

Documentation for individual rules can be found on the Rules website.

IDE-only

Secrets detection rules are only run in the IDE.

They do not appear in SonarQube/SonarCloud i.e. they can only be configured locally, and the secrets detection rules will not be run by the various Sonar scanners.

© 2008-2024 SonarSource SA. All rights reserved. SONAR, SONARSOURCE, SONARLINT, SONARQUBE, SONARCLOUD, and CLEAN AS YOU CODE are trademarks of SonarSource SA.

Creative Commons License