admin管理员组

文章数量:1594241

//

Code Analysis

ReSharper helps you analyze code on various levels, starting from a single statement in the editor and all the way through to the architecture of your entire solution.

Find code issues

ReSharper provides static code analysis (also known as code inspection) by applying over 2500code inspections in C#, VB.NET, XAML, XML, ASP.NET, ASP.NET MVC, Razor, JavaScript, TypeScript, HTML, CSS, ResX, and build script code, detecting compiler and runtime errors, suggesting corrections and improvements before you even compile.

By default, ReSharper starts analyzing a code file as soon as you open it in the editor, all the way you edit it, until it is closed. This design time inspection is performed silently by continuously applying all code inspections to your code. Not only ReSharper highlights code issues right in the editor according to their severity levels, it also adds its own marker bar to the right of the editor window, where you can see instantly the status of the file and jump to specific code issues, and provides commands for navigation between code issues.

If necessary, you can run code inspection for a specific project or the entire solution and check the list of issues found in the specified scope.

Also, you can enable the Solution-Wide Analysis that will detect all errors in your entire solution and extend the list of code inspections in the current file (for example it will find unused public members).

If needed, you can use code annotations to customize the way ReSharper inspects your code.

Another good thing is that you can define you own custom code inspections based on structural search and replace patterns, and specify severity level for them.

Quick-fixes for code issues

ReSharper helps you resolve most of the discovered code issues automatically. All you need is to press Alt+Enter when the caret is on a code issue highlighted in the editor and check the suggested quick-fixes.

Code exploration

ReSharper also provides features that do not detect code issues automatically, but rather allow you to find potential problems yourself by deeper investigation of the code. For instance, you canstudy call chains and find origin and destinations of a specific value. For more information on these features, see the Code Exploration section.

Type dependency analysis

ReSharper allows you to visually study how types depend on each other in your solution. In the type dependency diagram, you can add any number of types from different projects or compiled assemblies and visualize different kinds of dependencies between them. For more information, see Explore Type Dependency Diagram

Project dependency analysis

Some code issues may be discovered by analyzing the solution architecture. ReSharper can help you here with the project dependency analysis that allows you to visually explore project dependency diagram, find and optimize unused references, and detect possible architecture problems.

Code analysis from command line

If you need to integrate automatic code quality analysis into your CI, version control or any other server, you can use ReSharper Command Line Tools, which are free of charge and do not require ReSharper or Visual Studio to be running. The Command Line Tools package includes two tools for analysing code:

  • InspectCode, which executes hundreds of ReSharper code inspections
  • dupFinder, which detects duplicated code in the whole solution or narrower scope

Code analysis in supported languages

Most of ReSharper's code analysis features are available in C# and Visual Basic .NET, some are available in several languages, others are language-specific. The table below lists all code analysis features and languages/technologies where they are supported.

The instructions and examples given in the topics within this section address the use of code analysis features in C#. For more information on code analysis features available for specific languages, see the corresponding topics in the ReSharper by Language section.

Find Code Issues with Code Inspection

Static code analysis in ReSharper is called Code Inspection and performed by applying over 2300individual code inspections to your code in all supported languages.

Code issues can be found in several ways:

  • ReSharper finds and highlights code issues automatically in design time for all files opened in the editor.
  • The design time code inspection scope can be extended to the entire solution with the solution-wide analysis - in this case, you will be able to see all errors (and optionally warnings) in the solution as well as some additional issues in the opened files, for example unused public members.
  • You can find code issues in the specified scope, which can be as large as the whole solution.
  • You can also find code issues from the command line.

The easiest way to deal with code issues highlighted in the editor is to set the caret at the highlighted code item and press Alt+Enter or click the action indicator that appears to the left of the code issue. The action list will pop up where ReSharper suggests one or more quick-fixes for most issues.

You can extend the default set of code inspections with structural search and replace patterns, and get more inspections for specific purposes by using ReSharper extensions.

In this section:

  • Code Inspections
  • Detect Code Issues in Design Time
  • Find Code Issues in Specific Scope
  • Solution-Wide Analysis
  • Solution-Wide Code Inspections
  • Configure Code Inspection Settings
  • Create Custom Code Inspections and Quick-Fixes
  • Spell Checking with ReSpeller
  • Value and Nullability Analysis
  • Collection Access Analysis
  • Code Analysis and Helpers for String Literals
  • Use Annotations to Refine Code Inspection

If necessary, you can disable all inspections (except those detecting compiler errors) in a specific block of code by inserting // ReSharper Disable All before and// ReSharper Restore All after it, or in a specific type or member by adding the following attribute: [SuppressMessage("ReSharper", "All")].

Code Inspections

ReSharper provides over 2500 code inspections in all supported languages. These inspections are used to detect and highlight code issues in design time in all opened files, and/or to find all code issues in specific scope, which can be as large as the entire solution.

To find out what kind of code inspections ReSharper provides, check out the full list of ReSharper code inspections in different languages.

The easiest way to deal with code issues highlighted in the editor is to set the caret at the highlighted code item and press Alt+Enter or click the action indicator that appears to the left of the code issue. The action list will pop up where ReSharper suggests one or more quick-fixes for most issues.

Code inspections can be divided into the following groups:

  • ReSharper's own code inspections that include:
    • Inspections with the fixed severity level 'Error'. These inspections detect compiler errors and there is no way to disable or configure them.
    • Inspections with configurable severity levels, which detect the rest of code issues (for example, compiler warnings, runtime and logical errors, code smells, redundancies, improvement suggestions, and so on.). You can find these configurable inspections on theCode Inspection | Inspection Severity page of ReSharper options (Alt+R O). These inspections can be configured in several ways — you can suppress the detected issues with comments and attributes, disable them or change their severity level in settings or.editorconfig files.
  • Custom code inspections defined as structural search and replace patterns, which also have configurable severity levels.

You can get more inspections for specific purposes with ReSharper extensions.

Severity levels of code inspections

Each ReSharper code inspection as well as structural search and replace pattern has one of the following severity levels:

You can find default severity levels and other properties for each configurable inspection in the Code Inspection Index— just choose a language page and then use the browser search to find the details of the desired inspection.

Error

Code inspections that have the 'Error' severity level by default are aimed at code issues that either prevent your code from compiling or result in runtime errors. Most of these inspections are not configurable, that is you cannot disable them or change their severity level.

In design-time inspection, ReSharper displays unresolved symbols in red:

Code issues that are found with inspections having the 'Error' severity level, appear in theErrors/Warnings in Solution window if the Solution-Wide Analysis is enabled.

Warning

This severity level corresponds to compiler warnings and to other issues that do not prevent your code from compiling but may nevertheless represent serious coding inefficiencies. For example, ReSharper informs you about redundant type casts or namespace import directives, incorrect format strings, declared but never used local variables or private fields, unused private methods, and so on.

In design-time inspection, ReSharper displays redundant symbols with greyed text:

Warnings also appear in the Errors/Warnings in Solution window if the Solution-Wide Analysiswith warnings is enabled

Suggestion

Code issues with this severity level provide insights into code structure, drawing your attention to things that aren't necessarily bad or wrong, but probably useful to know.

For instance, you might be interested to know that 'parameter can be declared with base type', meaning that your method only uses members of the parameter's base type. This can be an indication of a different error, such as failure to take into account the specifics of the actual parameter type. Based on this knowledge, you may want to change the parameter's type - or not, if that is by design.

In design-time inspection, ReSharper highlights suggestions with a green curly underline:

Hint

This is the lowest severity level. Code issues with this severity bring your attention to a particular code detail and/or recommends a way of improvement.

In design-time inspection, ReSharper highlights hints by adding a dashed green underline to the initial two letters of the corresponding symbol:

Unlike errors, warnings and suggestions, hints are not taken into account when you navigate between code issues in the editor, and not shown in the marker bar.

Note that when you set the caret over a highlighted hint, no popup is shown, the corresponding message only appears in the status bar.

If necessary, you can disable any configurable code inspection.

In Visual Studio project settings, you can choose to treat warnings as errors. ReSharper is aware of this option and highlights warnings accordingly: if this setting is on, then issues that correspond to compiler warnings will be highlighted as errors. This setting is configurable in the project properties: Project | [Project Name] Properties | Treat warnings as errors and can be applied to all warnings if All is selected or to the specified warnings only.

Severity levels of most code inspections (except those detecting compiler errors) can be changed, that is you can define severity levels for each code inspection according to your needs.

When you inspect code in specific scope, ReSharper adds corresponding icons to the detected issues and allows sorting issues by the severity level in the Inspection Results window.

Categories of code inspections

ReSharper groups configurable code inspections by several categories. These categories roughly define purposes of inspections and kinds of code issues that they detect. The categories are used to group code inspections on the Code Inspection | Inspection Severity page of ReSharper options (Alt+R O), and to group code issues found in specific scope and displayed in theInspection Results window.

  • Potential Code Quality Issues 
    This category includes inspections that detect critical issues (code smells), mostly with Error orWarning level. This category also includes inspections that ensure localization assistance.
  • Common Practices and Code Improvements 
    This category groups inspections that hunt for medium severity issues that mainly affect code readability.
  • Redundancies in Code 
    Code inspections in this category look for redundancies and dead code, which affect code readability and style, and could be safely removed. Some code redundancies cannot be fixed automatically, and quick-fixes for them are performed in the interactive mode, requiring the user input. But the majority of the redundancies can be fixed without user interaction, using either fix in scope or code cleanup.
  • Language Usage Opportunities 
    This category includes code inspections, mostly with the suggestion severity level, which notify you when more advanced language constructs can be used. These inspections detect syntax of outdated language versions and suggest using features from more modern language versions. For most of the supported languages, language version can be detected automatically or set manually.
  • Code Notifications 
    This category groups code inspections with minor severity levels.
  • Code Style 
    Inspections in this category detect violations of code syntax styles. In contrast to most of other code inspections, these inspections can either detect the same code construct as a code issue or not depending on the corresponding code style rule configured on the Code Editing | [Language] | Syntax Style page of ReSharper options (Alt+R O). You can also fix issues that these inspection detect using code cleanup.
  • Constraints Violations 
    This category includes code inspections, mostly with the warning severity level, which detect violations related to symbol attributes, including ReSharper's code annotations, and other similar issues.
  • Redundancies in Symbol Declaration 
    This category includes code inspections, mostly with the warning severity level, which detect empty and unused symbol declarations.
  • Compiler Warnings 
    Inspections in this category detect compiler warnings before you compile.
  • Spelling Issues 
    These inspections detect typos in various contexts.
  • Not Runnable Tests 
    These inspections detect tests that cannot be executed.
  • NUnit 
    These inspections detect code issues related to NUnit tests.
  • Xunit 
    These inspections detect code issues related to xUnit.Net tests.
  • Formatting 
    Inspections in this category detect code code formatting problems.
  • Clang-Tidy Checks 
    Inspections in this category are provided by Clang-Tidy— a powerful open-source code analysis tool integrated with ReSharper.
  • Clang 
    Inspections in this category correspond to Clang compiler warnings integrated with ReSharper.
  • Clang Static Analyzer Checks 
    Inspections in this category are diagnostics from Clang Static Analyzer integrated with ReSharper. 
    All static analyzer checks are disabled by default, since enabling them significantly slows down Clang-Tidy.
  • Unreal Engine 
    Inspections in this category are specific to C++ code of Unreal Engine projects.

Identifiers of configurable code inspections

Each configurable code inspection has two unique identifiers that you can use to configure it. Let's take the Possible 'System.NullReferenceException' inspection as an example:

  • Inspection ID is used to suppress the inspection with a comment —
// ReSharper disable once PossibleNullReferenceException

for a single issue or

// ReSharper disable PossibleNullReferenceException

till the end of the file, 
or with an attribute —

[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
  • Inspection EditorConfig property can be used to configure the inspection from .editorconfig files. For example, you can change the inspection's severity level to Error with the following line:
resharper_possible_null_reference_exception_highlighting=error

You can find identifiers for each configurable inspection in the Code Inspection Index— just choose a language page and then use the browser search to find the details of the desired inspection.

List of configurable code inspections

  • Code Inspections in C#
  • Code Inspections in VB.NET
  • Code Inspections in JavaScript
  • Code Inspections in TypeScript
  • Code Inspections in C++
  • Code Inspections in XAML
  • Code Inspections in HTML
  • Code Inspections in CSS
  • Code Inspections in ASP.NET
  • Code Inspections in HttpHandler or WebService
  • Code Inspections in Razor
  • Code Inspections in Regular expressions
  • Code Inspections in Resource files
  • Code Inspections in Web.config
  • Code Inspections in MSBuild
  • Code Inspections in NAnt
  • Code Inspections in XML

Detect Code Issues in Design Time

ReSharper starts analyzing a code file as soon as you open it in the editor, all the way you edit it, until it is closed. All detected code issues are highlighted in the editor according to their severity levels. The map of the issues is also displayed on the marker bar in the right part of the editor window, where you can see instantly the status of the file and click the marks to navigate to specific code issues.

Product also allows you to use JSLint, ESLint, and TSLint to validate and fix JavaScript/TypeScript code right in the editor.

Design-time inspection features

To illustrate the design-time code inspection performed by ReSharper, consider the following code excerpt displayed in the editor:

  1. Status indicator that helps you to see at once whether the current file has errors or warnings.
  2. A fix popup that appears for non-imported types. It is enough to press Alt+Enter or click this popup and ReSharper will add the missing directive for all types in the file. For more information, see Import Missing Namespaces.
  3. A low-priority code issue (in this case, a suggestion related to an unused public member) is greyed out.
  4. A medium-priority code issue (in this case, a warning about a symbol name that does not fit with the naming style) is highlighted with a blue curly underline.
  5. A marker corresponding to the suggestion issue (3) is displayed on the marker bar.
  6. A marker corresponding to the error issue (8) is displayed on the marker bar.
  7. An action indicator that appears to the left of the caret position if ReSharper has anything to suggest there.
  8. A high-priority code issues (in this case, errors related to an unresolved symbol and an incorrect return type) are highlighted with red text and red curly underline.
  9. A marker corresponding to the warning issue (4) is displayed on the marker bar.
  10. The action list, which opens by pressing Alt+Enter or clicking the action indicator (7), contains a list of quick-fixes for the issue at the caret.
  11. A short description of the issue at the caret appears in the status bar. You can also view descriptions of code issues by hovering the mouse over highlighted code or over the issue markers on the marker bar (5,6,9)
  12. If the solution-wide analysis is enabled, ReSharper allows you to see even more code issues. In this example, it detects the unused public member (3) and notifies about errors in other files of your solution. You can click the solution-wide analysis icon to explore the detected issues.
  13. To make missing function returns, missing breaks in switch statements, and disposed resources more noticeable, use Code analysis hints.

Toggle design-time inspection

By default, design-time code inspection is enabled in all supported languages. However, you can disable it everywhere or turn it off for specific files if needed. For more information on configuring code inspection, see Configure Code Inspection Settings.

If you want to exclude the current file from code inspection, press Ctrl+Alt+Shift+8and ReSharper will add this file to the list of excluded files.

If you open a file excluded from code inspection, you can recognize it by the corresponding icon   of the status indicator. To quickly toggle code analysis for the current file, press Ctrl+Alt+Shift+8.

  1. Select ReSharper | Options from the main menu or press Alt+R O, then chooseCode Inspection | Settings on the left.
  2. Use the Enable code analysis checkbox to toggle the design-time code inspection.
  3. Optionally, you can enable or disable design-time inspection features on this page:

Color identifiers

This option lets you enable or disable ReSharper syntax highlightingscheme. 
If it is selected, language identifiers are highlighted with colors as defined in Visual Studio options: Tools | Options | Environment | Fonts and Colors
The list of syntax identifiers provided by ReSharper is available in theDisplay items list, each name starting with ReSharper prefix.

Note that by disabling this option you also disable symbol information tooltips that appear on mouse over.

This option does not affect C++. To toggle syntax highlighting in C++, use the corresponding option on theCode Editing | C++ | Inspections page of ReSharper options .

Highlight color usages

Enables highlighting of color definitions in code. For more information, see Color Assistance.

Highlight special characters in string literals

Enables highlighting of correct and incorrect escape sequences in non-verbatim strings. For example:

For more information, see Regular Expressions Assistance.

Highlight context exits

This option, enabled by default, tells ReSharper to highlight all places where the control flow can exit the current context. For example, for a method, it will highlight the return type of the method, all return,throw keywords, and so on when you set the caret to one of these identifiers

For a loop, it will additionally highlight the loop keyword as well as all the break statements inside this loop. 
Note that if a method is not entirely visible in the editor, you can invoke the Navigate To Function Exits command on the method name to trigger another kind of highlighting, which will not disappear when your caret leaves the method name.

  1. If necessary, you can select the Enable solution-wide analysis checkbox to enable the Solution-Wide Analysis.
  2. Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

Navigate code issues

If the design-time code inspection is enabled, you can easily navigate between all issues (except those with the hint severity level) detected in the current file.

Navigate to the next/previous code issue in the current file

  • Press Alt+PageDown to go to the next code issue, or Alt+PageUp to go to the previous code issue.
  • In the main menu, choose ReSharper | Inspect | Next Issue in File or ReSharper | Inspect | Previous Issue in File. .
  • Use the marker bar on the right side of the editor window: clicking on markers brings the caret to the corresponding issues; clicking on the status indicator on top of the marker bar brings the caret to the next issue in the file.
  • Right-click the status indicator and choose Go to Next/Previous Error/Warning/Suggestion— these commands will help you navigate between code issues of the highest severity level. So if there are errors, they only navigate between errors, as soon as all errors are fixed they navigate between warnings, and so on.

Another way of navigating between code issues is to run code inspection in the desired scope and then study the issues in a dedicated tool window.

If you are only interested in errors in the current file, you can jump between them skipping issues with lower severity levels. Besides, if you enable the Solution-Wide Analysis, you can jump between errors in the entire solution. Note that names of the navigation commands in theReSharper | Inspect menu change if the solution-wide analysis is on. Specifically, Next Error/Warning changes to Next Error/Warning in Solution and Previous Error/Warningbecomes Previous Error/Warning in Solution.

Navigate to the next/previous error

  • Press Alt+Shift+PageDown to go to the next error, or Alt+Shift+PageUp to go to the previous error.
  • In the main menu, choose ReSharper | Inspect | Next Error/Warning or ReSharper | Inspect | Previous Error/Warning.
  • If the Solution-Wide Analysis is enabled and there are some errors, the number of errors is displayed in the right corner of the status bar. You can click this number to go to the next error in the solution.

If you are not interested in some code issue, press Alt+Enter while you at the issue and select Inspection [name of inspection]. Then you can choose to suppress the corresponding code inspection for this issue or disable this inspection altogether.

Inspection options menu

Besides suggested fixes, for each configurable code inspection as well as for custom inspections, ReSharper shows the Inspection [name of inspection]  sub-menu in the actions list, with the following items:

  • Disable once with comment
  • Disable and restore with comment
  • Configure inspection severity
  • Find all issues of this type
  • For the most controversial issues, there is the Why is ReSharper suggesting this? item that opens a Code Inspection Index page with detailed description of the corresponding inspection.

Find similar issues

You can not only fix a highlighted issue with a quick-fix, but also find and investigate all similar issues (all issues detected with the same code inspection) in the whole solution or smaller scope.

Alternatively to looking for similar issues, that is applying a single code inspection in the desired scope, you can apply the entire set of ReSharper's inspections in this scope.

Find similar issues

  1. Set the caret at a highlighted issue in the editor.
  2. Press Alt+Enter or click the action indicator to the left of the caret to open theaction list.
  3. To find similar issues in the current file, choose Inspection [name of inspection] | Find similar issues in [filename] file.
  4. To find similar issues in the current project or solution, expand the submenu and choose the desired scope:

  1. If necessary, you can search for similar issues in any project or solution folder within your solution. To do so, choose Find similar issues in custom scope in the submenu.
    In the dialog that opens, type the name of the desired project or solution folder, and then click 
    OK.
  2. All found issues will be displayed in the Inspection Results window.

Integration with Visual Studio code inspection controls

Starting from version 2015, Visual Studio comes with its own code analysis engine (Roslyn) and provides its own light bulbs feature to perform quick actions including refactoring and fixing errors.

Visual Studio's quick actions often perform the same fixes as ReSharper's quick-fixescontext action, or refactorings. Therefore, for some errors you may have two similar suggestions from Visual Studio and from ReSharper. In the illustration below, you can see two bulbs both suggesting to remove redundant using directives:

To avoid this, ReSharper provides the Hide Visual Studio light bulb option on the Environment | Editor | Visual Studio Features page of ReSharper options. This option is enabled by default, so you will not see the duplicated bulbs unless you disable it.

If Visual Studio Light Bulb is suppressed, Visual Studio actions can be integrated into ReSharper'saction list by selecting the Merge Visual Studio light bulb actions into ReSharper action indicator checkbox. If it is selected, ReSharper does the following for each Visual Studio's quick action:

  • If there is a similar ReSharper's quick-fix or context action, the Visual Studio's quick action is not displayed.
  • If there are no similar ReSharper's action, the Visual Studio's action becomes available in the ReSharper's action list. You can recognize Visual Studio's quick actions by the special icon  .

If necessary, you can also disable Visual Studio's error highlighting in the editor, so that only code issues found by ReSharper are highlighted. To do so, select Hide Visual Studio squiggles on theEnvironment | Editor | Visual Studio Features page of ReSharper options.

Find Code Issues in Specific Scope

Design-time code inspection is a great help when you are coding in the editor or reviewing specific files. However, ReSharper also allows you to run static code analysis in the whole solution or narrower scope and examine the results in a friendly view. You can even share inspection results if necessary.

You can also inspect code in a specific scope from the command line without starting Visual Studio and ReSharper.

Start code inspection

Inspect code in solution, project or in a custom scope

  1. Decide whether you want the results of the solution-wide inspections (for example, unused public members) to be included in the report. If you want these results to be included, enable the solution wide-analysis. Note that when the solution-wide analysis is enabled, ReSharper has to analyze the whole solution even if you need to inspect a single project, so be prepared that it takes more time.
  2. Do one of the following:

In the main menu, choose ReSharper | Inspect | Code Issues in Solution orReSharper | Inspect | Code Issues in Current Project.

In the Solution Explorer, select items (files, folders, projects, solution folders) that you want to inspect, right-click the selection and choose Find Code Issues in the context menu.

In the Architecture View, select one or more items, right-click the selection and choose Find Code Issues in the context menu.

  1. The Inspection Results window will open displaying detected code issues.

Analyze inspection results

In the Inspection Results window, you can view the list of discovered code issues and locate them in the editor by double-clicking the entries:

Each new run of code inspection opens a new tab in the window so the results of previous runs are preserved until you close their tabs.

By default, issues are grouped by files. If necessary, you can regroup issues by type, severity, and so on using the Group by: selector.

To check context of the selected code issue, use the Preview pane that displays one or more lines related to the issue in the code file. Use the Show Preview selector to open the pane at the bottom or on the right of the window.

Filter inspection results

When you inspect code, ReSharper apply code inspections with all severity levels. However, issues detected with inspections of 'Hint' severity are filtered out by default. If necessary, you can customize filtering of code issues.

Note that the selected filtering affects the way code issues are filtered in the current tab and the way issues are filtered the next time you run code inspection.

Filter issues in the inspection results

  • If you want to hide issues of some type or hide all other issues except issues of this type, right-click a code issue and choose Hide All [Issue type] Issues or Show Only [Issue type] Issues correspondingly.
  • For more precise filtering, click Filter Issues  on the toolbar and use the Filter Issues dialog to specify issue types that should be displayed. The Defaults button in this dialog restores the default filtering when issues with severity levels of 'Hint' are filtered out.

Share inspection results

In large projects, code inspection results can be used im many different ways. For instance, to assign found issues to different developers: you can copy or export a code issue or a group of issues and submit the copy to an issue tracker.

Both Inspection Results window and Errors/Warnings in Solution window allow exporting code issues into text, HTML, or XML files.

Export inspection results to a file

  1. Open code inspection results in the Inspection Results window or enable the solution-wide analysis and open the list of errors in the Errors/Warnings in Solution window.
  2. Click Export on the toolbar to export the data currently displayed in the window in text format , or use the drop-down selector to export the data in XML or HTML format. The Export Data dialog that appears, will help you to save the data to a file or copy it to the clipboard .
  3. An alternative way to export current issues to an XML report, is to choose ReSharper | Inspect | Save Issues Report in the main menu and then specify filename and location.

Saving inspection results to the XML format has several advantages: first, this format is compatible with the output format of the InspectCode command-line tool and JetBrains TeamCity, second, you can later load and study it in th the Inspection Results window. Regardless of the tool that was used to generate the XML report, you can always open and examine it with ReSharper.

Study inspection results saved in an XML report

  1. In the main menu, choose ReSharper | Inspect | Load Saved Issues Report.
  2. Select an XML report file and click Open.
  3. The report is opened in a new tab of the Inspection Results window. If the current solution corresponds to that of the XML report, you will be able to navigate to the issues by double-clicking on the inspection result items.

Besides exporting, you can copy individual entries or custom selections of entries shown in theInspection Results window and Errors/Warnings in Solution window to the clipboard. The copied issue information include names of project and solution, filename and line number as well as the description of the issue. For example:

Solution MySolution.sln 
Project MyProject 
MyProject\About.aspx.cs:2 Using directive is not required by the code and can be safely removed

Copy information on found issues to the clipboard

  1. Select one or more code issues, or issue groups in the Inspection Results window orErrors/Warnings in Solution window.
  2. Right-click the selection and choose Copy in the context menu.
  3. Paste the copied issues where appropriate.

Solution-Wide Analysis

Solution-wide analysis finds errors in all supported languages, including ones that do not prevent your project from compiling. If your project includes such files (for example JavaScript, CSS, HTML), solution-wide analysis will help you find errors that could be otherwise only detected in runtime.

ReSharper's solution-wide analysis enables two related but distinct features:

Solution-wide errors/warnings monitor, which lets you constantly keep track of all errors/warnings in your solution: both compiler errors/warnings and errors/warnings detected by ReSharper’s own inspections. This feature works together with the design-time code inspection and brings two advantages:

You do not have to open every file to make sure that your solution does not contain errors/warnings.

If you delete a public member or change its visibility, the code in the current file can still be correct, but what if this member is used somewhere else in the solution? For example, suppose that you changed the visibility of a member from public to internal, assuming that it was only used inside the current project. At this stage, ReSharper finds no errors in the current file. Then, you switch on the solution-wide analysis , and actually there are errors. You can jump to the next error in solution and find out that someone uses this member from another project in your solution.

You can choose to monitor only errors or both errors and warnings in the solution-wide analysis.

Solution-wide code inspections , which help find issues that can only be detected by analysing the whole solution (unused public types and members, unassigned public fields, suspicious type conversions and so on). When the solution-wide analysis is enabled, issues detected by the solution-wide inspections are highlighted in the opened files in the same way as other issues, and they also appear in the Inspection Results window when you run code inspection in specific scope.

Enable solution-wide analysis

Solution-wide analysis can take some time for the initial processing of the solution and therefore, it is disabled by default. You should switch it on explicitly for every new solution you open.

Toggle solution-wide analysis

  1. On the Code Inspection | Settings page of ReSharper options (Alt+R, O), make sure that the Enable code analysis checkbox is selected, and click Enable solution-wide analysis. Optionally, you can enable or disable warnings in the solution-wide analysis.
  2. Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

Alternatively, you can right-click the circle indicator in the right corner of the status bar and use the context menu to toggle the solution-wide analysis. If the solution-wide analysis is off, just double-click the gray circle.

In large solutions, solution-wide analysis may result in some performance degradation, especially at the initial analysis phase. However, there are several ways to improve the performance of solution-wide analysis.

After you have switched on the solution-wide analysis, several changes are made:

The status-bar indicator displays the progress of the analysis. After the analysis completes, the indicator turns green (if no errors/warnings were found), orange (if warnings in the solution-wide analysis are enabled and if there are warnings in the solution), or red (if errors were discovered):

A small area to the left of the circle indicator is allocated to show the number of solution files that contain errors/warning, if any. You can click this area to go to next error/warning in the solution.

Solution-wide code inspections for non-private members become available both in the design-time code inspection and when you inspect code in a specific scope.

You can view the list of ReSharper's configurable code inspections on the Code Inspection | Inspection Severity page of ReSharper options (Alt+R, O). Solution-wide inspections can be recognized by the Non-private accessibility tag.

Names and semantics of the navigation commands in the ReSharper | Inspect menu change. Specifically, Next Error/Warning changes to Next Error/Warning in Solution and Previous Error/Warning becomes Previous Error/Warning in Solution.

While the solution-wide analysis is enabled, you can use the status bar indicator to monitor errors/warnings in solution, but you can also get a detailed report on all errors/warnings in your solution in the Errors/Warnings in Solution window.

You can share found issues by copying them to the clipboard or exporting to a file.

View the list of errors found in solution

  1. Do one of the following:

Choose ReSharper | Windows | Solution Errors in the main menu.

Right-click the circle indicator in the right corner of the status bar and chooseShow Errors View from the list.

Double-click the circle indicator.

  1. Either way, the Errors/Warnings in Solution window opens where you can view the list of detected errors/warnings and navigate to the related code by double-clicking the entries:

Even without opening this window, you can still easily navigate through errors in your solution with Alt+F12Shift+Alt+F12 (ReSharper | Inspect | Next Error/WarningReSharper | Inspect | Previous Error/Warning) , or just by clicking the number of errors/warnings to the left of the status bar indicator.

As an alternative to monitoring errors/warnings in solution, you can find all issues in your solution or smaller scope and view them in the Inspection Results window.

Performance of solution-wide analysis

The main calculations of the solution-wide analysis are performed when you first enable it. Depending on the size of your solution, these calculations may take from several seconds up to dozens of minutes. You will still be able to keep working, but some performance degradation is possible.

Once these global time-consuming calculations are finished, only necessary incremental analysis will be performed according to modifications.

When enabled, solution-wide analysis might also extensively use memory. If you notice that your system resources suffer too much, you can do one of the following:

Configure the list of files, file masks, and folders to skip when performing code analysis.

Edit the list of files and regions containing generated code to simplify analysis of such code.

Pause the analysis when you do not need it and resume it only when you need it again.

Exclude warnings from the analysis.

If you turn the solution-wide analysis off and then decide to turn it on again, ReSharper will have to repeat some of the initial calculations, which may be time-consuming. To avoid this, you can pause and resume the solution-wide analysis instead.

Pause and resume solution-wide analysis

On the toolbar of the Errors/Warnings in Solution window, click Pause Analysis  orContinue Analysis .

Right-click on the circle indicator in the right corner of the status bar and then choosePause Analysis or Continue Analysis in the context menu.

When warnings are enabled in the solution-wide analysis, it works as follows: as long as there are errors in the solution, only errors will be displayed; unresolved warnings will only appear when the last error is fixed. When warnings are disabled, the status bar indicator will turn green as soon as the last error is fixed.

Include/exclude warnings in solution-wide analysis

On the toolbar of the Errors/Warnings in Solution window, click Include/Exclude Warnings .

On the Code Inspection | Settings page of ReSharper options, use the Include warnings checkbox under Enable solution-wide analysis.

Ignore errors/warnings in solution

At some stage of your solution development, you may have too many errors/warnings known to you. ReSharper allows you to flexibly ignore some errors or error-containing files and not include them into solution-wide analysis results.

Such items will be hidden from the error list in the Errors/Warnings in Solution window and they will not affect the state of the status bar indicator. When necessary, you can stop ignoring these items to display them.

Allow solution-wide analysis ignoring specific errors/warnings

  1. In the Errors/Warnings in Solution window, select a discovered problem or, if you want to ignore all issues in a specific file, select this file.
  2. Click Ignore Error(s)  on the toolbar.
  3. To view the ignored errors/warnings, click Show Ignored errors/warnings  on the toolbar — you will see all errors/warnings in the solution, the ignored items are shown as crossed out. Even if you choose to display ignored items in the list, they will not affect the status bar indicator.

Stop ignoring specific errors/warnings in solution

  1. On the toolbar of the Errors/Warnings in Solution window, click Show Ignored errors/warnings .
  2. Select an ignored item or file. Such items are shown as crossed out.
  3. Click Stop Ignoring Error(s)  to stop ignoring the selected item.

Solution-Wide Code Inspections

Most of ReSharper's code inspections only need the source code of a single file to detect code issues. In addition to these inspections, ReSharper provides solution-wide inspections for code issues which are only detectable in the scope of the entire solution — for example to detect an unused non-private member ReSharper needs to analyze the entire solution.

For the solution-wide inspection to work, you need either or both of the following:

The simplified global usage checking is enabled —Show unused non-private type members when solution-wide analysis is off on the Code Inspection | Settings page of ReSharper options (Alt+R, O).

The solution-wide analysis is enabled —Enable solution-wide analysis on the Code Inspection | Settings page of ReSharper options (Alt+R, O).

Note that even if a symbol has no direct usages in your solution and ReSharper warns you about it, there could be cases where symbols are used indirectly — for example, via reflection — or they could just be designed as public API. In all those cases you would want to suppress the usage-checking inspection for the symbol, and there are several ways to do so:

The recommended way is to decorate the implicitly used symbols with code annotation attributes. There are two attributes for this purpose: [UsedImplicitly] and [PublicAPI], which are functionally similar, but let you and your teammates understand how the symbol is actually used.

You can also suppress usage-checking inspections with any custom attribute. To do so, mark the definition of that attribute with the [MeansImplicitUse] attribute.

And finally, you can suppress a specific usage-checking inspection as any other code inspectionwith a suppression comment or a suppression attribute.

Similarly to any other inspection, you can also disable or change severity level of any solution-wide inspection. This can be done right from the Alt+Enter menu on a code issue that the inspection highlights. Alternatively, you can disable/enable or change severity levels of inspections on the Code Inspection | Inspection Severity page of ReSharper options (Alt+R, O)— solution-wide inspections are marked with the Non-private accessibility label. Note that you cannot set the 'Error' severity for solution-wide inspections.

When the solution-wide analysis is enabled, issues detected by the solution-wide inspections arehighlighted in the opened files in the same way as other issues, and they also appear in theInspection Results window when you run code inspection in specific scope. However, they do not appear in the Errors/Warnings in Solution window.

Usually ReSharper provides one or several quick-fixes for each solution-wide inspection.

If necessary, you can disable solution-wide inspections or only enable solution-wide inspections on internal symbols for specific projects. To do so, use the Solution-Wide Inspections selector in the Project Item Properties popup, which you can invoke by selecting Edit project item properties from the context menu of the project in the Solution Explorer. 
Note that independently of the value in this selector, solution-wide inspections would be disabled if the solution-wide analysis is disabled in ReSharper options.

ReSharper provides the following solution-wide inspections:

Configure Code Inspection Settings

You can also use code annotations to customize the way ReSharper inspects your code.

Configure design-time code inspection

By default, ReSharper enables design-time code inspection in all files corresponding to thesupported languages. If necessary, you can disable it. Regardless of whether or not the design-time code inspection is enabled, you can always run code inspection in specific scope.

  1. Select ReSharper | Options from the main menu or press Alt+R O, then chooseCode Inspection | Settings on the left.
  2. Use the Enable code analysis checkbox to toggle the design-time code inspection.
  3. Optionally, you can enable or disable design-time inspection features on this page:

Color identifiers

This option lets you enable or disable ReSharper syntax highlightingscheme. 
If it is selected, language identifiers are highlighted with colors as defined in Visual Studio options: Tools | Options | Environment | Fonts and Colors
The list of syntax identifiers provided by ReSharper is available in theDisplay items list, each name starting with the ReSharper prefix.

Note that by disabling this option you also disable symbol information tooltips that appear on mouse over.

This option does not affect C++. To toggle syntax highlighting in C++, use the corresponding option on theCode Editing | C++ | Inspections page of ReSharper options .

Highlight color usages

Enables highlighting of color definitions in code. For more information, see Color Assistance.

Highlight special characters in string literals

Enables highlighting of correct and incorrect escape sequences in non-verbatim strings. For example:

For more information, see Regular Expressions Assistance.

Highlight context exits

This option, enabled by default, tells ReSharper to highlight all places where the control flow can exit the current context. For example, for a method, it will highlight the return type of the method, all return,throw keywords, and so on when you set the caret to one of these identifiers

For a loop, it will additionally highlight the loop keyword as well as all the break statements inside this loop. 
Note that if a method is not entirely visible in the editor, you can invoke the Navigate To Function Exits command on the method name to trigger another kind of highlighting, which will not disappear when your caret leaves the method name.

4.If necessary, you can select the Enable solution-wide analysis checkbox to enable the Solution-Wide Analysis.

5.Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

Exclude files and folders from code inspection

ReSharper allows you to configure the list of files, file masks, and folders that should be excluded from code inspection. The excluded items are ignored by both design-time code inspection andcode inspection in specific scope, but they are still indexed by ReSharper, so that you can navigate to or refactor symbols excluded from code inspection.

Exclude specific files and folders from code inspection

  1. Select ReSharper | Options from the main menu or press Alt+R O, then chooseCode Inspection | Ignored Code on the left.
  2. In the left part of the Elements to skip section, you can specify files or folders to be ignored by the code inspection.
  3. In the right part of this section, you can specify masks (for example *.vb) that will exclude all matching files in the solution from code inspection.
  4. Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

You can also quickly exclude the current file from code inspection so that ReSharper adds this file to the list of excluded files without opening the options.

Exclude/include current file from/to code inspection

Press Ctrl+Alt+Shift+8.

Right-click the status indicator and choose Pause/Resume analysis.

If you open a file excluded from code inspection, you can recognize it by the corresponding icon of the status indicator.

Exclude frozen projects from indexing

On the the Code Inspection | Ignored Code page of ReSharper options (Alt+R, O), you can also use the Projects to ignore list to specify projects that should be completely ignored by ReSharper.

The ignored projects will not be indexed by ReSharper, meaning that no ReSharper features — for example, Code Analysis, Refactorings, Code Generation— will be available in those projects.

This list is mainly intended to improve performance by not indexing and not analyzing projects that contain third-party code or frozen code, which is not going to be changed.

Although the source files in the ignored projects are not parsed, ReSharper will still process the compiled code from the output of those projects (which is very cheap performance-wise). This means that after you build the ignored projects, ReSharper will correctly resolve usages of symbols from those projects and you will be able to enjoy Navigate and Search in those projects.

So if after adding some projects to the ignore list, you have errors like 'Cannot resolve symbol', you need to build the ignored projects and ReSharper will be able to resolve those symbols from the compiled artifacts.

To add projects to the ignore list, either use project file names, for example ProjectOne.csproj or file for examples, for example Project*.csproj to match ProjectOne.csprojProjectTwo.csproj, and so on.

Partly disable code inspection for generated code

You can also configure the list of files, folders, file masks, and regions that contain generated code. For these items, ReSharper runs only those code inspections that check code for compiler errors and warnings. Some file masks and regions, which are typically used for generated code, for example *.designer.cs are included in this list by default, but you can change the default settings if necessary.

Specify files and regions with generated code

  1. On the Code Inspection | Generated Code page of ReSharper options (Alt+R, O), use the Add File and the Add Folder buttons to specify files or folders that contain generated code.
  2. In the lower left part of the page, use the Add button to specify masks (for example*.Designer.cs) for generated code files.
  3. In the lower right part of the page, use the Add button to specify names of the regions that contain generated code.
  4. Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

The list of items containing generated code can also be used for disabling Code Style and Cleanup for generated code.

Change severity levels of code inspections

Each ReSharper's code inspection has its own default severity level, which is set according to potential impact of code issues that it detects. Most of the inspections have configurable severity level, which you can change.

Note that inspections that detect compiler errors and warnings have corresponding severity levels, which cannot be changed. However, with some compiler warnings, you can use #pragmadirectives to suppress them. Look for the suppress with #pragma action in the action list upon a specific warning.

You can change severity level of an inspection right from the editor, where a code issue found by this inspection is highlighted.

Change inspection severity from the editor

  1. Set the caret to a code issue highlighted by a ReSharper's inspection.
  2. Press Alt+Enter or click the action indicator to the left of the caret to open theaction list.
  3. In the action list, choose Inspection [name of inspection] | Configure inspection severity and then select a new severity level:

4.Your change will be saved using the smart save logic.

5.If you need to save the modified severity level in a shared settings layer, click theConfigure inspection severity menu item or press Enter when it is selected. In the dialog that appears, choose the desired severity level, click Save To and then choose the desired settings layer.

Another way to save the modified severity level in a shared settings layer, or modifying severity levels of multiple inspections is using the ReSharper Options dialog Alt+R, O as described below.

Modify severity levels of code inspections from options

  1. On the Code Inspection | Inspection Severity page of ReSharper options (Alt+R, O), you can view all configurable code inspections and their severity levels. The inspections are grouped by languages and then by categories.
  2. Find and select the inspection whose severity you want to modify. To find an inspection, just start typing its name.
  3. Click the list to the right of the selected entry, and choose a desired severity level:

4.If the default severity level of an inspection is changed, you will see the Reset to default  button next to it, which allows you to reset the severity to its default value.
The same button also appears next to the category where such inspection belongs, Clicking this button next to a category will reset all inspections inside the category to their default severity levels.

5.Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

Disable/enable specific code inspections

If some code inspection seems trivial or being of no interest to you, you can disable this inspection so that no relevant issues would be highlighted in the editor or detected when you run code inspection is specific scope. You can enable a disabled code inspection any time later. Some inspections are disabled by default and you can enable them if necessary.

You can disable any code inspection in one of the following ways:

  • If there is a code issue highlighted by this inspection in the editor, set the caret at the highlighted code, press Alt+Enter and then choose Inspection [name of inspection] | Configure inspection severity | Do not show.
  • On the Code Inspection | Inspection Severity page of ReSharper options (Alt+R, O), use the search box to find the inspection you want to disable or enable, and then use the checkbox next to it.

The disabled/enabled state of inspections is saved in the shared settings layers, exactly the same way as changes to severity levels.

Use EditorConfig to configure code inspections

If you use EditorConfig to maintain code styles for your project, you can also configure code inspections from .editorconfig files.

To configure code inspections from EditorConfig, you have to select the Read settings from editorconfig and project settings checkbox on the Code Inspection | Settings page of ReSharper options (Alt+R, O).

As EditorConfig convention suggests, ReSharper will apply inspection settings defined in files named .editorconfig in the directory of the current file and in all its parent directories until it reaches the root filepath or finds an EditorConfig file with root=true. File masks specified in.editorconfig files, for example *Test.cs are also taken into account.

Inspection settings in .editorconfig files are configured similarly to other properties — by adding the corresponding lines:

[inspection_editorconfig_property]=[error | warning | suggestion | hint | none]

For example, you can change the severity level of the Possible 'System.NullReferenceException'inspection to Error with the following line:

resharper_possible_null_reference_exception_highlighting=error

Inspection settings from .editorconfig files have higher priority than the settings configured on the Code Inspection | Inspection Severity page of ReSharper options (Alt+R, O).

You can find EditorConfig property for each inspection on pages in the Code Inspection Indexsection as well as on the Index of EditorConfig properties page. — just use the browser search to find the property for the desired inspection.

Suppress code inspections in specific scope

One way to ignore specific code issues is to disable the corresponding code inspection. In this case, all code issues detected by this inspection will be ignored everywhere. 
Sometimes you may need to suppress a specific inspection in a specific place, while continue to detect other similar issues with this inspection in other places. 
For example, ReSharper considers some code to be 'dead' and you can see that it is true. The inspection is helpful and you do not want to disable it. However, you may want to use this code later and do not want it to be 
highlighted in the editor or appear in the inspection results. To do so, ReSharper allows you to suppress inspections with comments or with attributes. Comments are more convenient for arbitrary pieces of code, attributes are preferable to suppress inspections in whole methods or types.

Suppress code inspection in specific scope

  1. Set the caret to a code issue highlighted by a ReSharper's inspection.
  2. Press Alt+Enter or click the action indicator to the left of the caret to open theaction list.
  3. In the action list, choose one of the following:

Inspection [name of inspection] | Disable once with comment— this option inserts a single comment ReSharper disable once [inspection id], which only suppresses the inspection for the first occurrence of the corresponding issue.

Inspection [name of inspection] | Disable once with comment | Disable in file with comment — this option inserts a single comment -ReSharper disable [inspection id] in the beginning of the file. This comment suppresses the inspection for all corresponding issues in the file.      

Inspection [name of inspection] | Disable once with comment | Disable and restore with comment — this option inserts a pair of comments before and after the issue - ReSharper disable [inspection id] andReSharper restore [inspection id]. These comments suppress the inspection for all corresponding issues between them. 
You can then move these comments to other places in the file so that several issues of this type are suppressed. For example, this can be useful to suppress the 'redundant namespace' inspection if you want to keep several unused namespace imports.

Inspection [name of inspection] | Disable once with comment | Disable for method — this option adds the following attribute to the method:[SuppressMessage("ReSharper", "[inspection id]")]. This attribute suppresses the inspection in the method.

Inspection [name of inspection] | Disable once with comment | Disable for class — this option adds the following attribute to the class:[SuppressMessage("ReSharper", "[inspection id]")]. This attribute suppresses the inspection in the whole class.

Inspection [name of inspection] | Disable once with comment | Disable all inspection in file — this option inserts a single commentReSharper disable All in the beginning of the file. This comment suppresses all inspections the file. 
If necessary, you can insert the 
ReSharper restore All to enable code inspections after a specific line.

You can find identifiers for each configurable inspection in the Code Inspection Index— just choose a language page and then use the browser search to find the details of the desired inspection.

To suppress all inspections in a type or a method, add the following attribute:[SuppressMessage("ReSharper", "All")].

Create Custom Code Inspections and Quick-Fixes

If you see an issue or a bad practice in your code, but ReSharper does not detect it, you can create a custom code inspection. Additionally, you can specify code that should replace the problematic code, in other words, a custom quick-fix.

If the custom inspection is created correctly, it will be able to find all similar issues in your codebase and highlight the problematic code right in the editor.

To create custom inspections, you can harness the Structural Search and Replace mechanism.

To illustrate creating custom inspection, let's imagine that we do not like the following code:

string line;
var tr = new MyReader();
try
{
line = tr.Read();
}
finally
{
tr.Dispose();
}
.. and would rather replace it with:
string line;
using(var tr = new MyReader())
{
line = tr.Read();
}

Create a custom code inspection with a quick-fix

  1. In the editor, select a piece of code that should be considered as a problem.
  2. Right-click the selection and choose Search with Pattern.
  3. ReSharper displays the Search with Pattern dialog with the selected code pre-parsed as the search pattern. Some identifiers, arguments, types, and so on, are automatically replaced with placeholders:

 

  1. To make the inspection pattern more universal, edit the recognized placeholders: and replace other code items with more placeholders. For instance, we can replace the single statement in the try block in our example, with a placeholder that matches any number of statements.
  2. To specify a quick-fix for the problem, click Replace in the right upper corner of the dialog. 
    In the 
    Replace pattern area, specify a pattern that should be used to replace the problematic code. Use the same placeholders for the variable code items. 
    Here is how the refined pattern and a quick-fix would look for our example:

 

  1. Click Save and then Close when finished. The custom inspection is saved in the pattern catalog using the smart save logic. 
    Note that the problematic piece of code is not yet highlighted in the editor. We need to do a couple of things more to make it work.
  2. In the main menu, select ReSharper | Options and go to the Code Inspection | Custom Patterns page.
  3. In the list of patterns, find the pattern that corresponds to the custom inspection you've just created. By default its severity level is set to 'Do not show', which means that ReSharper will ignore the issues corresponding to your custom inspection. 
    To enable the inspection, choose any other severity level, for example, 'Suggestion'.
  4. Lastly, we can specify descriptions that will be shown for the custom inspection and the corresponding quick-fix.

To do so, double-click the pattern and then, in the Edit Highlighting Pattern dialog that opens, specify the descriptions in the corresponding fields:

You can specify a 'suppression key' for a pattern - an identifier that you can use to suppress ReSharper inspection that detects usage of the pattern, with a comment.

 

  1. Save changes to the pattern, close it, and then click Save again on the Custom Patterns page of the ReSharper options.

Now the problem is recognized and highlighted in the editor. The specified description appears when you hover the mouse over it:

As we have refined the inspection pattern, it will find similar problems even with different number of arguments in the constructor call or different number of statements:

The quick-fix for the custom inspection looks and works exactly the same as the built-in quick-fixes.

If you need to find the problem described by your custom pattern in a larger scope, you have several options:

  • Choose the inspection pattern on the Code Inspection | Custom Patterns page of ReSharper options and click Search Now on the page toolbar.
  • Run code inspection in the desired scope and then analyze your custom problems with the rest of detected code issues.
  • Use the Find Similar Issues action that appears in the inspection options when you pressAlt+Enter on the highlighted code in the editor.

Spell Checking with ReSpeller

One important task of code inspection is spell checking, which ReSharper performs with ReSpeller — its integrated spell-checking engine. ReSpeller will look for spelling mistakes in identifiers, comments, and string literals. When it detects a potential spelling mistake or a typo, it will let you know in the same way as other code issues —in design time or when you run code inspection is specific scope.

Spell checking is enabled by default, but you can disable it by clearing the corresponding checkbox on the Tools | ReSpeller page of ReSharper options (Alt+R, O).

Similarly to other highlighted issues, you can press Alt+Enter and choose Replace with… to choose one of the ReSpeller's suggestions.

If you use the ReSpeller's quick-fix to fix a typo in an identifier, the Rename refactoring will be invoked automatically to ensure consistency of the change across your code base.

ReSpeller dictionaries

ReSharper comes with a built-in dictionary for English (United States), but it allows you to install and use Hunspell /MySpell dictionaries for other languages. A lot of dictionaries can be found on https://github/wooorm/dictionaries.

Install custom dictionaries

  1. Select ReSharper | Options from the main menu or press Alt+R O, then chooseTools | ReSpeller on the left.
  2. Add the desired Hunspell/MySpell dictionaries — click   and pick a Hunspell dictionary file .dic. Note that you also need to have the affix file of the dictionary (named the same as the dictionary file but with the .aff extension) next to the dictionary file.
  3. While you are at this page, you can specify which kinds of identifiers and strings should be spell-checked and which should not.
  4. Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

When you install a custom dictionary, ReSharper saves a full path to the dictionary file in settings. If you share your solution via VCS, you can share custom dictionaries by putting dictionary files in the VCS directory and making the paths in the settings file relative.

Share custom dictionaries

  1. Put the desired dictionary files in your solution directory. For example, you can create a Dictionaries subdirectory in the solution root and put the files there.
  2. Add the dictionaries in settings as described above, make sure to save changes in the'Solution team-shared' settings layer.
  3. In the solution root folder, find and open the team-shared settings file<SolutionName>.sln.DotSettings.
  4. In the settings file, find all entries that define dictionaries — they start with<s:Boolean x:Key="/Default/InstalledDictionaries— and specify relative paths for them.

For example, if you put German dictionary files German.dic and German.aff in theDictionaries subdirectory in the solution root, then the entry for the dictionary will look as follows in the settings file:

<s:Boolean x:Key="/Default/InstalledDictionaries/=_005CDictionaries_005CGerman_002Edic/@EntryIndexedValue">True</s:Boolean>

The path format in settings uses the following symbol substitutions:

_003A for :

_005C for \

_002E for .

  1. Make sure that <SolutionName>.sln.DotSettings file and all dictionary files are committed to your VCS.

You can extend the installed dictionaries with other words, which will be stored using the settings layers together with other preferences. There are two ways to add user words:

When your caret is on a highlighted spelling issue in the editor, choose Add to user dictionaryfrom the Alt+Enter menu. The word will be saved using the smart save logic, but you can also expand the submenu to choose a specific settings layer:

On the Tools | ReSpeller page of ReSharper options (Alt+R, O), use the User words field to configure a newline-separated list of words to be ignored by the spell-checker.

Configure ReSpeller inspections

By default, ReSpeller inspections are enabled in many of ReSharper’s supported languages. You can enable/disable individual inspections and change their severity levels by searching for typoon the Code Inspection | Inspection Severity page of ReSharper options (Alt+R, O).

You can disable ReSpeller by clearing the ReSpeller checkbox on the Environment | Products & Features page of ReSharper options (Alt+R, O) .

Value and Nullability Analysis

ReSharper performs value analysis to help you find possible 'null' dereferences as well as redundant boolean comparisons and null checks.

Different ways of analyzing values

ReSharper analyzes values in two general ways:

By understanding the behavior of language constructs.

In the example below, based on the fact that the parameter obj was explicitly checked for nullability, ReSharper reasonably supposes that the value of obj can be indeed 'null' and displays the corresponding warning:

By relying on code annotation attributes ([CanBeNull][NotNull][ItemCanBeNull],[ItemNotNull])

In this example, the method Bar is marked with the [CanBeNull] attribute, Using this information, ReSharper warns you that the return value of Bar can be null, and calling a method on it could lead to a 'null' dereference:

If necessary, you can make code analysis even more precise with Contract Annotations. They help you define dependencies between arguments of a function and its return value.

You can instantly fix these problems (for example automatically add a nullability check) using quick-fixes.

Value and nullability analysis modes

ReSharper can analyze values in different modes:

Optimistic 
By default, value analysis mode is optimistic. In this mode, ReSharper only warns about possible 'null' dereference if the value was explicitly checked for nullability, or if the symbol is marked with the 
[CanBeNull] or [ItemCanBeNull] attribute. The optimistic mode is demonstrated in the examples above.

Pessimistic 
In this mode, ReSharper warns about possible 'null' dereference in all contexts where the value is not checked for nullability explicitly, unless the symbol is marked with the 
[NotNull] or[ItemNotNull] attribute.

To change value analysis mode or disable the analysis, configure the Value analysis modepreference on the Code Inspection | Settings page of ReSharper options (Alt+R, O).

Further examples of value analysis

Here are some more examples of ReSharper's value and nullability analysis:

If a nullability check has been already done with a simple LINQ query, ReSharper tells you that a further nullability check is redundant:

The same happens if you mark a collection with the [ItemNotNull] attribute:

The next example illustrates how value analysis works when the pessimistic mode is enabled. The value of the list was checked for nullability, but not list items. Therefore ReSharper warns here about possible 'null' dereference.

Collection Access Analysis

Besides analyzing values of collection items, ReSharper also analyzes each collection you use as a whole — it warns you when a collection is never filled or modified even if there is a read access to this collection:

or instead, if a collection is never read:

All standard collection types are analyzed this way by default. If necessary, you can also apply this analysis to your custom collections that derive from IEnumerable. In this case, you need to tell ReSharper how invocations of collection’s public methods will affect the contents of the collection. To do so, mark the methods of your collection class with the[CollectionAccessAttribute], which should have one of four flags: NoneRead,ModifyExisitingContentUpdatedContent (the difference between the last two flags is thatUpdatedContent means that the marked function can also add new elements to the collection). Here is a simple example to illustrate this:

Code Analysis and Helpers for String Literals

ReSharper provides a bunch of features for string literals in your code. You can benefit from ReSharper's code analysis and numerous helpers in:

Plain strings

Here is how ReSharper can help you when you are working with plain strings in your code:

By default, ReSharper highlights correct and incorrect escape sequences in all non-verbatim strings:

 

You can convert regular strings to verbatim strings and back by pressing Alt+Enter when your caret is in the string and choosing the corresponding context actions. This also works with interpolated strings.

You can split string literals simply by pressing Enter.

If a string contains regular expression, ReSharper can highlight its syntax and errors, and help you with code completion inside the expression. For more information, see Regular Expressions Assistance
Similarly, you can make ReSharper analyze HTML in string literals. To make ReSharper aware of the specific language inside a string literal, you can either use the corresponding 
context actionsor add a comment /*language=regexp|jsregexp|html*/ right before the string literal.

You can select some substring within a string and automatically introduce a variable for the substring.

If your project is localizable, you can automatically move a string to resource.

String formatting methods

ReSharper analyzes format strings and arguments of all .NET string formatting methods, such asString.FormatText.StringBuilder.AppendFormat, or Console.WriteLine.

In usages of string formatting methods, ReSharper highlights format placeholders and also synchronously highlights placeholder with the corresponding argument when your caret is at either of them:

If arguments and format placeholders mismatch (which leads to the FormatException in runtime if arguments are missing), ReSharper generates warnings for missing or redundant arguments:

You can easily fix this problem by pressing Alt+Enter over the warning. ReSharper will suggest either to automatically add the missing argument or to remove the mismatched format placeholder.

ReSharper also helps you detect and remove redundant calls of string formatting methods inside other string formatting methods. For example:

To quickly convert a concatenation of string literals and variables, press Alt+Enter anywhere within the concatenation and use the To String.Format invocation context action. For example, if we apply this context action in the return statement of the following method:

public string Greet(string name, int age)

{

    return "Hi, my name is " + name + " and I'm " + age;

}

It will be converted to:

public string Greet(string name, int age)

{

    return String.Format("Hi, my name is {0} and I'm {1}", name, age);

}

You can also use context actions to automatically add and remove format placeholders and arguments in strings. When you invoke the Insert format argument action within a string literal, ReSharper inserts a new placeholder with the proper index and brings you to the position where you can immediately start typing the argument. This action can also be invoked on a plain string. In this case ReSharper will automatically convert it to the String.Format call.

In order to quickly remove a format placeholder together with the corresponding argument, set the caret at the placeholder, press Alt+Enter and choose Remove format argument.

Custom string formatting methods

When a custom string formatting method appears, you have to tell ReSharper to interpret it as such, which is quite easy - you need to decorate the method with the[StringFormatMethodAttribute] from the JetBrains.Annotations namespace. As soon as the method has this attribute, you will enjoy all features available for standard formatting methods.

Consider a custom string formatting method ShowError:

public void ShowError(string formatString, params object[] args)

{

    // some custom logic

    Console.WriteLine(formatString, args);

}

If the method is called incorrectly, as shown below, ReSharper has no chance to detect the missing argument:

ShowError(“Failed:{0}”);

Make ReSharper aware of a custom string formatting method

  1. Reference the JetBrains.Annotations namespace as described in the Annotations in Source Code section.
  2. Annotate your custom string formatting method with the[StringFormatMethodAttribute] attribute, which takes a single argument - the name of the format string parameter:

[StringFormatMethod("formatString")]

public void ShowError(string formatString, params object[] args)

{

    // some custom logic

    Console.WriteLine(formatString, args);

}

ReSharper will now be able to warn you about missing arguments when this custom formatting method is invoked. Even more, the Add argument quick-fix will make it easier for you to insert them:

You can annotate custom string formatting methods in compiled libraries using External Annotations.

Interpolated strings

If you are using C# 6.0 in your project, you can use interpolated strings instead of theString.Format method.

By default, ReSharper automatically detects C# version based on the associated compiler. However, you can specify the target C# version explicitly — right-click the project in the Solution Explorer, choose Edit project item properties from the context menu and use the C# Language Level selector. .

In C# 6.0 projects, ReSharper highlights usages of String.Format with the suggestion to convert them into interpolated strings. You can use a quick-fix to convert the current usage or all usagesin the specific scope with a couple of keystrokes.

If an interpolated string contains no expressions, ReSharper highlights the $ sign as redundant and helps you remove it:

If you need to quickly add the $ at the beginning of the string when you deep into typing out the string, you can press Alt+Enter and choose To string interpolation
You can then also choose Insert interpolated argument and ReSharper will add the argument placeholder { } at your caret position.

Use Annotations to Refine Code Inspection

Code inspection and many other ReSharper features largely rely on knowing behavior of language constructs to detect issues, suggest possible improvements, and help you in other ways.

However, this kind of analysis cannot detect everything. For example, if a method is designed to never return null and its clients are designed accordingly, no structural analysis will find a possible issue if someone has changed the method to return null.

In this and a lot of other cases, the ReSharper's JetBrains.Annotations is of a great help. By using attributes declared in this framework you can make ReSharper analyze code the way you need it. For example:

[NotNull]

public object Foo()

{

    return null; // Warning: Possible 'null' assignment

}

This being the simplest example, there are other helpful attributes with more complex use cases. You can find the full list of these attributes in the reference.

In most cases, code annotation attributes enable specific code inspections, for example:

StringFormatMethodAttribute helps detect misuses of string formatting methods.

CanBeNullAttribute and NotNullAttribute are associated with the Possible 'null' assignment to entity marked with 'Value cannot be null' attribute. For more information, seeValue and Nullability Analysis.

CannotApplyEqualityOperatorAttribute is bound to the Code Inspection: Compare with '==' types marked by 'CannotApplyEqualityOperatorAttribute'.

ContractAnnotationAttribute can be used to define contracts for your functions and turn on the corresponding inspections. For example, you can use[ContractAnnotation("input:null => false")] to notify the consumers of the functionbool Foo(object input) that always returns false when parameter s is null.

Also, code annotations enable more quick-fixescode completion suggestions, and code generation features on annotated items. The annotations are also required to create and useSource Templates.

ReSharper allows you to annotate code symbols in two ways:

You can annotate symbols in your source code as shown in the example above. In this case, you need to reference JetBrains.Annotations namespace in your project. For more information, see Annotations in Source Code.

Even if you do not have access to sources, you can annotate symbols in compiled library code. For more information, see External Annotations.

Part of the work of annotating standard libraries (for example .NET Framework Class Library, NUnit Framework) with external annotations is already done and the external annotations for these libraries are included in the ReSharper installation. So you can benefit from attributes driven inspections, quick-fixes, and other features when using these libraries.

Annotations in Source Code

The easiest way to benefit from ReSharper's code annotations is to add the annotation attributes to symbols of your source code and make ReSharper analyze your solution with greater accuracy and insight.

By default, all annotation attribute classes are marked with[Conditional("JETBRAINS_ANNOTATIONS")] attribute so the compiler will ignore the attribute usages in your code, which means that no binary reference to the 'JetBrains.Annotations.dll' assembly will be produced. However, you can define 'JETBRAINS_ANNOTATIONS' conditional compilation symbol in your projects to preserve the attributes in the metadata.

Enable code annotations support in your project

To make use of ReSharper code annotation attributes in your project, you should reference them in one of the following ways:

The recommended way is to install the NuGet package with the JetBrains.Annotationsassembly. 
Actually, you do not even need to go to the NuGet website to get the package. Just add the
using JetBrains.Annotations; directive, and use the corresponding Alt+Enter action to automatically fetch the package.

You can add a project reference to the JetBrains.Annotations.dll, which you can find in the ReSharper installation directory.

You can also embed attribute declarations anywhere in your project, using the defaultJetBrains.Annotations namespace, or any other namespace.

If the JetBrains.Annotations.dll is referenced or attribute declarations are embedded in any of the projects within your solution, you can type the desired annotation attribute and pressAlt+Enter to invoke the quick-fix that will reference this module in the current project and add the missing namespace import directive:

Alternatively, you can press Ctrl+Alt+Space twice to invoke the double import completion, which will find the attribute, import the namespace, and add the reference.

Embed declarations of code annotations in your source code

You can get a copy of the code-annotations declarations on the Code Inspection | Code Annotations page of ReSharper options (Alt+R, O). Optionally, when copying you can choose to make the declarations internal and/or add the [Conditional("JETBRAINS_ANNOTATIONS")]attribute to the declarations.

The default implementation of the annotation attributes are declared in theJetBrains.Annotations namespace, but this namespace is not required for the annotations to work. You can put the declarations anywhere in your solution — ReSharper will detect them automatically. However, if the declarations are in a different namespace you should explicitly specify the namespace with annotation attributes as described below. 
There also may be cases when your solution contains several implementations of the annotation attributes, for example, you have classes with the same names as ReSharper annotations classes (
CanBeNullAttributeNotNullAttribute, and so on) or you are using a third-party assembly that contains ReSharper annotation classes. In such cases, you can choose namespaces where ReSharper should look for the proper set of the annotations-attributes classes.

Change sources of code annotation attributes

  1. Select ReSharper | Options from the main menu or press Alt+R O, then chooseCode Inspection | Code Annotations on the left.
  2. All namespaces (from both source code and referenced assemblies) other thanJetBrains.Annotations with the annotation classes (ReSharper will only look forCanBeNullAttribute and NotNullAttribute declarations) are shown in theNamespaces with code annotation attributes list. Check the entry that contains the desired implementation.
  3. If there are several namespaces in the list, select the one that should be used by the ReSharper code analysis engine it in the Default annotation namespace list.
  4. Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using theSave To list. For more information, see Manage and Share ReSharper Settings.

Use Context Actions to add annotation attributes

As soon as ReSharper is aware of annotation classes location, you can use context actions to add the most popular annotation attributes:

[NotNull]

[CanBeNull]

[UsedImplicitly]

To add these annotations, press Alt+Enter on the symbol you want to annotate, and ReSharper will suggest an attribute depending on the context:

External Annotations

How it works

If you are using an external library, whose sources are not available to you, it does not seem feasible to use the attributes there for specifying code annotations.

In this case, you can use External Annotations, which allow you to complement the already compiled entities with attributes recognized by ReSharper's code analysis engine. External annotations let you 'cheat' the engine, by making it see the attributes (for methods, parameters and other declarations), which were not declared at the time the library was compiled.

External annotations are specified in XML files. When loading solution, ReSharper looks for specifically named XML files in specific locations and reads annotations from there. These XML files have a structure similar to XmlDoc. For example, to annotate the methodXmlReader.Create(Stream input) from the assembly System.Xml of .NET Framework 4.0, with the NotNull contracts, the XML file would look as follows:

<assembly name="System.Xml, Version=4.0.0.0">

    <!--The attribute name contains the assembly name. If you don't specify the version,

    this file's attributes will be applied to all versions of the assemblies of that name -->

    <member name="M:System.Xml.XmlReader.Create(System.IO.Stream)">

        <!--This shows the name of the member whose attributes are complemented;

        the notation is the same as XmlDoc -->

        <attribute ctor="M:JetBrains.Annotations.NotNullAttribute.#ctor" />

            <!--attribute constructor names are also specified using XmlDoc notation -->

        <parameter name="input">

            <attribute ctor="M:JetBrains.Annotations.NotNullAttribute.#ctor" />

        </parameter>

    </member>

</assembly>

JetBrains external annotations

The approach described above was used to annotate a huge amount of symbols in the .NET Framework Class Library, as well as in other frequently used libraries. External annotations for these libraries are installed with ReSharper to ensure better code analysis. Some features (for example, ASP.NET MVC 5.2 support) are also rely on external annotations.

The source code of JetBrains external annotations is available under the MIT license on GitHub:https://github/JetBrains/ExternalAnnotations. You are welcome to contribute to this repository or use it as an example for your own external annotations.

Create external annotations

You can create external annotations to specify contracts for any compiled assembly. To make sure ReSharper recognizes the XML file with external annotations, this file should be named[Assembly.Name].ExternalAnnotations.xml. Depending on how you are going to use the annotated binaries, you can create annotations files in the following places:

  • If you are going to publish some binaries (for example, via NuGet), place the annotations[Assembly.Name].ExternalAnnotations.xml file in the same folder where the annotated[Assembly.Name].dll file is located.
  • If you want to annotate some binaries included in your project, place the annotations files for each assembly in the ExternalAnnotations folder next to the project or solution file.

When you put an annotations file in this folder, the file should be named after the assembly name, that is [Assembly.Name].xml. It can also be in a subfolder of ExternalAnnotations, but that folder must have the assembly name, that isExternalAnnotations/[Assembly.Name]/[AnyName].xml

This way you can also keep the annotations under a VCS so that your team could benefit from them.

You can use ReSharper annotations as a reference when creating your own annotations. To study ReSharper external annotations, look at XML files in subdirectories of the[ReSharper installation directory]\ExternalAnnotations directory.

To illustrate creating external annotations, imagine that you use a TestLib assembly that hasMyTestClass class with static string ReverseString(String inputString) method. Suppose, that from the assembly documentation, you know that the method is pure and never returns null, and its parameter should never be null.

Initially, ReSharper is not aware of how ReverseString works, and therefore it finds no problems in the following code:

Create external annotations for a compiled assembly

  1. Locate the TestLib.dll on your file system and create a file namedTestLib.ExternalAnnotations.xml either in the same folder or in theExternalAnnotations folder next to the project or solution file where TestLib.dll is referenced.
  2. Open TestLib.ExternalAnnotations.xml for editing and type in the following:
<assembly name="TestLib">
<member name="M:TestLib.MyTestClass.ReverseString(System.String)">       
<attribute ctor="M:JetBrains.Annotations.NotNullAttribute.#ctor" />       
<attribute ctor="M:JetBrains.Annotations.PureAttribute.#ctor" />        
<parameter name="inputString">           
<attribute ctor="M:JetBrains.Annotations.NotNullAttribute.#ctor" />      
</parameter>   
</member>
</assembly>
  1. Reload your solution. Now ReSharper detects incorrect usage of ReverseString and highlights the problem with the null parameter:

 

... and the unnecessary check of the return value:

 

  1. To see, which external annotations are applied to a library symbol, you can use theQuick Documentation feature. Just press Ctrl+Q over the symbol to study its attributes. In our case, we can see that ReverseString is annotated with [NotNull]and [Pure] attributes and the parameter is annotated with [NotNull]:

 

The grey color of the attributes means that they come not from assembly code, but from external annotations.

To get the correct symbol IDs for the name attributes in your annotations, use theCopy XML-Doc ID to Clipboard command on original symbols.

Distribute external annotations

Another case of using external annotations is publishing external annotations for a library that you distribute, or for any library you like. In this case, the users of your library who also use ReSharper or Rider, will get more suggestions and fixes.

External annotations for libraries can be published on and installed from ReSharper gallery as NuGet packages. To learn more about packaging external annotations, see ReSharper plugin development guide.

Contract Annotations

Contract annotations let you define expected outputs for given inputs, or put in other words, define dependencies between reference type and boolean arguments of a function and its return value. The mechanism of contract annotations allows creating APIs that could be consumed in easier and safer way.

Sometimes you may want to use simpler alternatives instead of contract annotations. For example, if your function never returns 'null' independently on the input, you can use the [NotNull] attribute. For more information, see Value and Nullability Analysis.

You can implement contract annotations by decorating your functions with the[ContractAnnotationAttribute]. If you want to do it in your source code, reference the JetBrains.Annotations namespace. You can also annotate functions in existing binary modules using External Annotations.

How it works

To quickly understand how and why you could use contract annotations, look at the example below.

In this example, we decorated the function Adjust with the contract annotation attribute. The attribute argument in this case means, that a null argument always yields a null return. You can easily read the code of this example to see that the function works this way, but in real-life code this dependency might not be that obvious. Anyway, the main thing here is the contract annotation attribute that describes how the function handles the input value.

When we call the Adjust function with a 'null' argument, ReSharper finds and highlights a bunch of issues at once. First of all, it highlights the function call with a null argument, warning that this expression is always null. Then, it keeps tracking the adjusted variable that was initialized with this expression, and now is also 'null'. When we check the adjusted variable for inequality to 'null', ReSharper warns us again that this comparison is always false. Finally, ReSharper greys out code in the 'if' statement as unreachable:

Syntax of contract annotations

Use the following syntax to specify input-output dependencies for contract annotations:

[ContractAnnotation("[paramName:][input]=>            
output [;[paramName:][input]=> output]",
[forceFullStates:true])]

The input can be:

  • null/notnull for reference type parameters
  • true/false for boolean parameters.

The output can be

  • null/notnull/canbenull for the return value of reference type
  • true/false for the return value of boolean type
  • halt|stop|void|nothing (which are interchangeable) to indicate that the function does not return normally. That is, it throws an exception or halts program execution.

The optional boolean forceFullStates parameter, which is false by default, allows you force thepessimistic mode for the nullability analysis. That is if the method return value is not defined by the contract condition, ReSharper will assume that it might be null.

Remarks:

  • You can omit paramName if there is only one parameter (see the example above)
  • You can omit both paramName and input if there are no parameters:
  • [ContractAnnotation("=> halt")]
public void TerminationMethod()

or if the function has the same output independently on the input:

[ContractAnnotation("=> halt")]
public void TerminationMethod(object data, bool flag)
  • You can add several conditions for the same parameter:
  • [ContractAnnotation("input:null => null; input:notnull=>notnull")]
public object Transform(object input, bool flag)
  • You can reverse conditions, that is input => output is equal to output <= input:
  • [ContractAnnotation("null <= param:null")]
public string GetName(string surname)
  • You can also specify expected values for 'out' parameters. If you want to specify both a return value and an 'out' parameter for the same input condition, use the comma:
  • [ContractAnnotation("s:null => false,result:null")]
public bool TryParse(string s, out object result)

Validation of contract conditions

If you decorate functions with contract annotation in the source code, ReSharper verifies contract conditions according to the function signature. If the contract annotation does not suit function parameters, ReSharper displays a warning:

The same happens if the contract annotation does not suit the return value.

Quick-Fixes for Code Issues

ReSharper helps you instantly repair most code issues that it detects in design time. It is as simple as pressing Alt+Enter at a highlighted code issue and choosing the appropriate way to fix the problem or improve the suboptimal code.

Apply quick-fixes

Quick-fixes are visually displayed as action indicators to the left of a highlighted code issue. These indicators appear when you set the caret at the code issue. The following indicators imply quick-fixes:

View and apply quick-fixes

  1. Use the issue highlighting in the editor and the marker bar to navigate to a specific code issue.
  2. Set the caret at the highlighted issue.
  3. Press Alt+Enter or click the action indicator to the left of the caret to open theaction list.
  4. Click the desired quick-fix or select it using arrow keys and then press Enter.

In most cases, a quick-fix is applied immediately. However, some quick-fixes (for example, Change All) require user interaction to chose how exactly they transform your code. In these cases, a Hot Spot Session is deployed in the editor, where you can select one of the suggested values or provide your own values in the active input positions:

To complete the hot spot session:

  • If ReSharper suggests some values for the current parameter, use Up and Down arrow keys to navigate through the list of suggested values, or just type in a desired value.
  • Press Tab or Enter to accept the value and move to the input position of the next parameter. If this is the last parameter, the hot spot session completes and the caret moves to the end position defined for the session.
  • Press Shift+Tab to move the input focus to the input position of the previous parameter.
  • Press Esc to exit the hot spot session. In this case, all session parameters will be initialized with default values.

Some quick fixes can be applied not only in the current caret position, but in a larger scope. For more information, see Fix in Scope.

The list of predefined quick-fixes can be extended with custom code inspections defined in the structural search and replace patterns.

Quick-fixes from Visual Studio

Starting from version 2015, Visual Studio comes with its own code analysis engine (Roslyn) and provides its own light bulbs feature to perform quick actions including refactoring and fixing errors.

Visual Studio's quick actions often perform the same fixes as ReSharper's quick-fixes, context action, or refactorings. Therefore, for some errors you may have two similar suggestions from Visual Studio and from ReSharper. In the illustration below, you can see two bulbs both suggesting to remove redundant using directives:

To avoid this, ReSharper provides the Hide Visual Studio light bulb option on the Environment | Editor | Visual Studio Features page of ReSharper options. This option is enabled by default, so you will not see the duplicated bulbs unless you disable it.

If Visual Studio Light Bulb is suppressed, Visual Studio actions can be integrated into ReSharper'saction list by selecting the Merge Visual Studio light bulb actions into ReSharper action indicator checkbox. If it is selected, ReSharper does the following for each Visual Studio's quick action:

If there is a similar ReSharper's quick-fix or context action, the Visual Studio's quick action is not displayed.

If there are no similar ReSharper's action, the Visual Studio's action becomes available in the ReSharper's action list. You can recognize Visual Studio's quick actions by the special icon  .

Examples of Quick-Fixes

Quick-fixes are available in a variety of circumstances, which is too large to be listed. ReSharper provides a total of more than 1200 quick-fixes in all supported languages. Here we will show how to use them using a small selection of situations:

Type mismatch

Whenever the type of an expression cannot be implicitly cast to the type applicable to the expression context, ReSharper detects this error and highlights it in the editor. After positioning the caret at the highlighted error and pressing Alt+Enter, you can choose a quick-fix from the following list:

The effects of applying the proposed quick-fixes are illustrated in the table below.

Undefined variable

Whenever ReSharper detects an undefined variable in your code, the error is highlighted. After positioning the caret at the highlighted error and pressing Alt+Enter you will be presented with the following list of quick-fixes:

The effects of applying the proposed quick-fixes are illustrated in the table below.

Undefined method call

Whenever ReSharper detects a call to an undefined method in your code, the error gets highlighted. After positioning the caret at the highlighted error and pressing Alt+Enter, ReSharper displays the following list of quick-fixes: 

After applying a quick-fix, the code gets modified as shown in the following table:

Forgotten method return

If a method is expected to return a value but you forgot to provide a return statement, ReSharper warns you about that by highlighting the closing bracket of the troublesome method. After positioning the caret at the highlighted error and pressing Alt+Enter you will be presented with the following quick-fixes:

Missing Using directives

Whenever you have a type name in your code that cannot be resolved because you forgot to write a corresponding using directive in your file, a small popup suggests to import the type:

Press Alt+Enter, and the appropriate using directive will be inserted. Should there be multiple types with the matching name, you will be asked to choose the one you wish to use (see Importing Namespaces for details).

If for some reason you chose not to import a required namespace when the popup was displayed, or if you disabled Show the "Import namespace" action using popup on the Code Inspection | Settings page of ReSharper options (Alt+R, O), you can import a type at any time by putting the caret at the non-imported type, pressing Alt+Enter and choosing the corresponding quick-fix.

You may want some types or namespaces not to be suggested, for example, if you have something similar to a system type in your solution, say MyFramework.MyCollections.List, but you are not actually using it. To exclude such symbols from the suggestions, add them to theExclude from import and completion list on the Code Inspection | Settings | Auto Import page of ReSharper options (Alt+R, O) . The format of the entries is Fully.Qualified.Name,Fully.Qualified.Name.Prefix*, or *Fully.Qualified.Name.Suffix. Generic types are specified as List`1.

Missing async modifier

If you have a method that contains the await operator, but that is not defined as asynchronous, ReSharper detects such mismatch and offers to fix this problem using the corresponding quick-fix.

Converting a loop to a LINQ expression

With C# 3.0 and LINQ, developers are able to write data-intensive code more easily by directly describing their intent to the compiler. ReSharper detects code that can be rewritten using LINQ syntax and offers to perform the conversion automatically:

Migrating to IEnumerable in method parameters and returns

ReSharper scans your code base to detect methods that can safely return and acceptIEnumerable instead of a more specific type such as ArrayList, or ArrayList:

Converting assignment statements to object initializers

ReSharper provides both a context action and a quick-fix to convert assignment statements into object initializers. The context action lets you add field assignments to an initializer one-by-one, whereas the quick-fix adds them all in one go. Here's how the quick-fix works:

Converting static method invocation to extension method call

When you invoke an extension method as a traditional C# static method, ReSharper helps you quickly comply with standard extension method call practices:

Converting anonymous method to lambda expression

ReSharper suggests converting anonymous methods to lambda expressions. The reverse functionality is provided as a context action.

Converting to auto-property

ReSharper makes it quick to convert traditional, private field-based properties to automatic properties implemented in C# 3.0. For more information, see Use Auto-Properties.

Making type parameter invariant

When a usage of a type parameter violates its variance, ReSharper suggests to make the parameter invariant:

Import Missing Namespaces

When you use types whose namespaces have not been imported in the file, ReSharper helps you locate these types and add the missing namespace import directives. If there are several missing namespaces for an unresolved type, for example, after you paste a block of code in the file, ReSharper would help you import all these namespaces in a single action.

ReSharper looks for non-imported namespaces in the following assemblies: assemblies referenced in the current project, assemblies referenced in other projects in the solution, assemblies that are referenced transitively. If the type is found in an module that is not referenced in the current project, ReSharper also suggests adding a reference to this module.

Alternatively to using non-imported types and then importing namespaces for them, you can use Import Symbol Completion, which helps finding types from related assemblies and imports the missing namespaces automatically.

The missing namespaces are imported according to your namespace import preferences (for example, import directives are inserted or type names qualifiers are added). 
The import directives are added in a fixed order: all System.* namespaces go first, sorted alphabetically by the second word after the dot; all other namespaces go next, in alphabetical order.

When you edit a code file, types with missing namespaces are detected with the design-time code inspection (so make sure that it is enabled) and highlighted as errors. By default, the action that imports missing namespaces differs from the normal quick-fix: it is displayed as a popup that hovers either over the first unresolved symbol regardless of your caret position:

or after a pasted code bock:

Thus, you can apply this fix for all unresolved types with the habitual Alt+Enter shortcut without changing your current caret position, so your editing session is not interrupted. Note that theImport types for pasted code action only appears if all non-imported types in the pasted code block can be unambiguously found in the referenced modules of the current project.

In case several namespace contain the unresolved symbol, ReSharper lets you choose the namespace to import:

If for some reason you chose not to import a required namespace when the popup was displayed, or if you disabled Show the "Import namespace" action using popup on the Code Inspection | Settings page of ReSharper options (Alt+R, O), you can import a type at any time by putting the caret at the non-imported type, pressing Alt+Enter and choosing the corresponding quick-fix.

To quickly choose whether to show import suggestions via the popup, or an entry in theAlt+Enter menu, use the context menu of the file status indicator:

You may want some namespaces not to be suggested, for example, if you have something similar to a system type in your solution, say MyFramework.MyCollections.List, but you are not actually using it. To exclude such symbols from the suggestions, add them to the Exclude from import and completion list on the Code Inspection | Settings | Auto Import page of ReSharper options (Alt+R, O) . The format of the entries is Fully.Qualified.Name,Fully.Qualified.Name.Prefix*, or *Fully.Qualified.Name.Suffix. Generic types are specified as List`1.

Fix in Scope

Most of quick-fixes can fix the current issue under the caret, but some of them (for exampleRemove unused directivesMake field read-onlyRemove redundant cast, and so on) can also automatically find and fix issues in a larger scope — in the current file, in the current project or in the whole solution.

imilarly to 'Fix in scope', some context actions can also be applied in a wider scope.

Apply fix in scope

You can recognize such fix by a small arrow displayed next to it in the action list.

Small fixes in a specific scope can also be done with the Code Cleanup.

Apply fix in scope

  1. Set the caret to a code issue highlighted by a ReSharper's inspection.
  2. Press Alt+Enter or click the action indicator to the left of the caret to open theaction list.
  3. Choose a quick-fix that you want to apply.
  4. Click the arrow to right of the quick-fix or press the right arrow key to expand the list of available scopes. If there is no arrow to the right of a quick-fix, then this quick-fix only applies locally.
  5. Select the scope for the quick-fix to apply and click it or press Enter.

All files where ReSharper applies fix in scope open in editor tabs. If necessary, you can undo all that was changed in these files with a single command: choose Edit | Undo in the main menu or press Ctrl+Z.

Fix inconsistent naming in scope

The quick-fix that fixes inconsistent naming, calls the Rename refactoring to make sure that all occurrences of the symbol are renamed in your solution.

Therefore, when you choose to fix naming in a wider scope, ReSharper displays an additional dialog where you can select items to rename:

List of quick-fixes that can be applied in wider scope

The full list of quick-fixes that can be applied in wider scopes includes:

ASP.NET

Optimize register directives

Remove redundant 'imports' in file

Remove unused directives in file (see Code Syntax Style: Namespace Imports)

C++

Add 'override' specifier to an overriding function

Add 'template' keyword

Add 'typename' keyword

Add 'virtual' specifier to an overriding function

Apply clang-tidy fix for []

Bulk make local var const

Bulk make local variable declaration const

Change smart pointer to make function

Delete redundant specifier

Delete redundant typename template keywords keyword

Join declaration and assignment

Make member function 'const'

Make member function 'static'

Remove all unused #include directives in file

Remove redundant 'else' keyword

Remove redundant member initializers

Remove redundant parentheses

Remove redundant qualifier

Remove statement

Remove unreachable code

Remove unused lambda capture

Replace expression with 'false'

Replace expression with 'nullptr'

Replace 'if' with 'if constexpr'

Replace import directive Fix slashes in import file path

Replace throw with rethrow

Replace with prefix operator

Sort #include directives in file

Sort member initializers by the order of initialization

Use 'auto'

Use static_cast

C#

Argument style Add missing/Remove redundant argument name (see Code Syntax Style: Named/Positional Arguments)

Arrange attributes Place attributes into single section (see Code Syntax Style: Multiple Attributes)

Arrange braces Add missing braces/Remove redundant braces (see Code Syntax Style: Braces for Single Nested Statements)

Arrange code body

Arrange default value

Arrange inconsistent qualifier (see Code Syntax Style: Optional Member Qualifiers)

Arrange object creation

Arrange redundant qualifier (see Code Syntax Style: Optional Member Qualifiers)

Arrange trailing comma

Clarify precedence with parentheses (see Code Syntax Style: Optional Parentheses)

Convert to auto-property (see Use Auto-Properties)

Convert to switch expression

Convert to 'switch' expression

Convert to 'switch' statement

Convert to 'using' declaration

Enforce deconstructing declaration style

Enforce discard declaration style

Fix built in type reference style use type keyword/CLR type name (see Code Syntax Style: Built-In Type References)

Import extension get enumerator method

Import extension get enumerator method popup

Import method (see Code Syntax Style: Namespace Imports)

Import method popup Import item and all other references (see Code Syntax Style: Namespace Imports)

Import type (see Import Missing Namespaces)

Import type quick popup (see Import Missing Namespaces)

Inline 'out' variable declaration

Join null check with assignment

Make auto-property get-only (see Make Auto-Properties Get-Only)

Make operator 'public static'

Make readonly Make fields readonly (see Make Fields Readonly)

Mark nullable (see Value and Nullability Analysis)

Merge conditional expression

Merge sequential checks

Merge sequential patterns

Move to '' namespace

Remove '()' (see Code Syntax Style: Optional Parentheses)

Remove 'abstract' keyword

Remove argument name specification (see Code Syntax Style: Named/Positional Arguments)

Remove 'as' operator

Remove attribute

Remove cast

Remove 'Cast<T>' call

Remove guard clause

Remove initializer

Remove invalid statement

Remove modifier

Remove 'new' modifier

Remove param type specification

Remove 'params' array creation

Remove 'partial' keyword

Remove prohibited modifier(s)

Remove property assignment

Remove redundant '?'

Remove redundant argument(s) value

Remove redundant 'ascending'

Remove redundant base constructor invocation

Remove redundant 'base()'

Remove redundant braces

Remove redundant 'catch'

Remove redundant comparison

Remove redundant condition

Remove redundant constructor

Remove redundant delegate constructor call

Remove redundant else

Remove redundant 'finally' block

Remove redundant fixed pointer declaration

Remove redundant 'int'

Remove redundant 'internal' modifier (see Code Syntax Style: Modifiers)

Remove redundant member initializer

Remove redundant name

Remove redundant 'new'

Remove redundant parentheses

Remove redundant parenthesis (see Code Syntax Style: Optional Parentheses)

Remove redundant range bound

Remove redundant section

Remove redundant signature

Remove redundant 'string.Format()' call (see Code Analysis and Helpers for String Literals)

Remove redundant 'ToCharArray()'

Remove redundant 'ToString' (see Code Analysis and Helpers for String Literals)

Remove redundant tuple component name

Remove redundant type arguments

Remove redundant type specification

Remove redundant verbatim prefix

Remove 'sealed' keyword

Remove semicolon

Remove statement

Remove 'unchecked' expression

Remove unnecessary whitespace

Remove 'unsafe' modifier

Remove unused directives in file

Remove unused label

Rename to ''

Replace 'unsafe' statement with its body

Replace with count access

Rethrow exception

Separate statements with blank line

Sort modifiers (see Code Syntax Style: Modifiers)

To compound assignment

To extension method invocation

To null-coalescing compound assignment

To object pattern

To regular string

To string literal

Unwrap from delegate creation

Use array initializer

Use async overload

Use 'await using'

Use base class qualifier

Use explicit type - Use 'var' or explicit type depending on the code style settings.

Use index from end expression

Use 'nameof' expression

Use null propagation

Use nullable short form

Use pattern matching

Use span type for stack alloc

Use string interpolation

Wrap with constructor

HTML

Add/change quotes

JavaScript

Add explicit 'null'

Add missing comma

Add/change quotes

Convert to template string

Fix property name

Json schema incompatibilities

Make all variables from this list block-scope

Move variable '' to inner block

Remove unexpected comma

Rename to ''

Terminate all unterminated statements in file

TypeScript

Change public modifier to conform style

Change to ECMAScript 6 'export default'

Convert cast to 'as' operator

Convert to ECMAScript 6 import statement

Fix relative path style

Js2 ts transformation

Remove redundant qualifier

Remove redundant reference comment

Remove redundant type specification

Remove unused 'import'

Specify '' explicitly

Specify variable type explicitly

VB.NET

Import type (see Import Missing Namespaces)

Import type quick popup (see Import Missing Namespaces)

Make auto-property get-only (see Make Auto-Properties Get-Only)

Make readonly Make fields readonly (see Make Fields Readonly)

Move to '' namespace

Remove 'ByVal' modifier

Remove redundant element

Remove redundant 'imports' in file

Remove redundant qualifier

Remove unused label

Rename to ''

To implicitly typed

Use string interpolation

V b make readonly Make field read-only (see Make Fields Readonly)

XAML

Remove element

Rename to ''

Code Exploration

In addition to Code Inspections, ReSharper's code analysis allows you to investigate members by building hierarchies, call chains and value chains. The Hierarchy window and Inspection Results window that display the results of these analyses, allow you to further explore the code and to navigate to specific investigation results.

Inspect This

ReSharper | Inspect | Inspect This… 
Ctrl+Shift+Alt+A 
ReSharper_InspectThis

This command is a shortcut to ReSharper's code exploration and inspection features:

Call Tracking

Value Tracking

Explore Type Hierarchy

Find code issues

Type dependency diagram

You can invoke this command from the Solution Explorer, from the File Structure window and other tool windows. Depending on the context, this shortcut helps you access all code-exploration features available in that context.

View contextually available code exploration features

  1. Place the caret at a symbol in the editor or select the symbol in a tool window.
  2. Press Ctrl+Shift+Alt+A or choose ReSharper | Inspect | Inspect This… from the main menu . Alternatively, you can press Ctrl+Shift+A, start typing the command name in the popup, and then choose it there.
  3. The Inspect This list appears.

  1. Choose an item from the list and click it or press Enter.

Call Tracking

ReSharper | Inspect | Incoming/Outgoing Calls 
ReSharper_CallHierarchyShowIncomingCalls / ReSharper_CallHierarchyShowIncomingCalls

Call Tracking enables you to view and navigate through call chains in your code. ReSharper Call Tracking is a substantial improvement over Visual Studio native Call Hierarchy, thanks to support for events, interfaces, and closures.

In the hierarchy view, ReSharper uses icons to distinguish between different kinds of symbols. You can learn meanings of the icons on the Symbol Icons Schemes reference page. If necessary, you can switch between icon sets in the using the Source code symbol icons theme radio buttons on the Environment | General page of ReSharper options.

Double-click a node in the Inspection Results window to navigate to the corresponding call in the editor.

Investigate outgoing calls

  1. Place the caret at the name of a method, event, property or constructor.
  2. In the main menu, choose ReSharper | Inspect | Outgoing Calls or pressCtrl+Shift+Alt+A and choose Outgoing Calls in the Inspect This list.
  3. In the Inspection Results window that opens, you can expand the member node to run code analysis on it and to display all members called by the current member. You can also expand each of the child nodes.

 

Investigate incoming calls

  1. Place the caret at the name of a method, event, property or constructor.
  2. In the main menu, choose ReSharper | Inspect | Incoming Calls or pressCtrl+Shift+Alt+A and choose Incoming Calls in the Inspect This list.
  3. In the Inspection Results window that opens, you can expand the member node to run code analysis and to display all members that call the current member. You can also expand each of the child nodes.

When you get a lot of calls in the call tracking results, you can hide specific calls or the whole branches of the result tree to have a clearer picture of what you are looking for. 
Note that when you switch between tabs in the Inspection Results window, the hidden entries are reset.

Hide entries from the result tree

  1. Right-click the entry that you want to hide and choose Ignore in the context menu.
  2. The entry becomes greyed out but it is still visible and searchable. Also the Show Ignored Usages   button appears on the toolbar.
  3. To hide or show ignored entries, toggle the Show Ignored Usages  button.
  4. To reset ignored entries, toggle on the Show Ignored Usages  button, right-click a greyed-out item, and choose Undo ignore in the context menu.

Value Tracking

ReSharper | Inspect | Value Origin/Destination 
ReSharper_DfaReachingDefinitionsUp / ReSharper_DfaReachingDefinitionsDown

Value Tracking helps you investigate value of a particular type and possibly determine how a certain incorrect value might have passed to a given point in your program, and where it might be passed next. This helps you investigate possible NullReferenceException, inappropriate behavior, and reasons why you get incorrect values.

Double-click any data flow element in the Inspection Results window to navigate to it in the editor.

Investigate member's value origins

  1. Place the caret at the name of a method, property, variable, field, and so on, whose value you want to investigate.
  2. In the main menu, choose ReSharper | Inspect | Value Origin or pressCtrl+Shift+Alt+A and choose Value Origin in the Inspect This list.
  3. In the Inspection Results window that opens, you can investigate possible origins of the value.

 

Investigate member's value destinations

  1. Place the caret at the name of a method, property, variable, field, and so on, whose value you want to investigate.
  2. In the main menu, choose ReSharper | Inspect | Value Destination or pressCtrl+Shift+Alt+A and choose Value Destination in the Inspect This list.
  3. The Inspection Results window opens where you can investigate possible destinations of the value.

If a node represents an element of a collection, it is marked with ; if there is a lambda expression, it is marked with .

Explore Type Hierarchy

ReSharper | Inspect | Hierarchies 
Ctrl+Alt+H 
ReSharper_TypeHierarchyBrowse

With ReSharper, you can investigate the inheritance hierarchy of types from your solution and from referenced libraries. You can see both base types and inheritors of the selected type and navigate to any of them with a mouse click. For any node in the hierarchy, you can view all or only polymorphic members in the preview pane.

You can also view hierarchy of CSS styles.

Investigate hierarchy

  1. Locate the desired type in the editor or expand it in the Solution Explorer.
  2. Press Ctrl+Alt+H or choose ReSharper | Inspect | Hierarchies from the main menu . Alternatively, you can press Ctrl+Shift+A, start typing the command name in the popup, and then choose it there.
  3. Examine type hierarchy in the dedicated tab that adds to the Hierarchy window.

Some symbols in the tree are displayed in a bold font. It means that they inherit directly from the type being examined.

Hierarchies can be rather complicated, making it difficult to find one particular symbol, especially when you have doubts about its name and place in the hierarchy. In such case you can start typing a part of symbol's name or its CamelHumps abbreviation and ReSharper narrows down the set of elements in the window:

If you want to see what modules contain symbols in the hierarchy, select Containing Modules Hierarchy in the Group by list.

If the Hierarchy window is closed, you can view and examine previously generated hierarchies at any time by choosing ReSharper | Windows | Hierarchies in the main menu. 
However, this command does not build any new hierarchies and the window may be empty if you have not built any hierarchies since the current solution has been open.

You can also visualize the current hierarchy on the type dependency diagram by clicking theShow on Diagram   on the toolbar.

Rebuild a hierarchy for an intermediate node

  1. In the hierarchy tree view, select the desired node.
  2. Click Base on This   on the toolbar or choose the corresponding command in the context menu of the selection.

Preview members of a type selected in the hierarchy

  1. Select a type in the hierarchy.
  2. Click Show Members   on the toolbar or press Ctrl+P. The members preview pane displays at the bottom of the window:

  1. You can move the preview pane to the right of the window by clicking the down arrow next to Show Members   on the toolbar and selecting Right.
  2. You can also preview either all members of a type, or just those that are polymorphic. To switch between these two modes, use the All Instance Members   and Only Polymorphic Members   buttons at the top of the preview pane.

You can reach all Refactorings available for members directly from the Hierarchy window— press Ctrl+Shift+R or right-click a member and choose a desired refactoring command in the context menu.

View Intermediate Language (IL)

ReSharper | Windows | IL Viewer 
ReSharper_ShowIlViewerWindow

ReSharper allows you to study your source code and decompiled symbols in the intermediate language (IL).

The intermediate language for source code becomes available after you build your project. 
If the source was modified after the build, the synchronization between the source and the IL code could be incorrect. The IL code will be updated as soon as you build the project again.

IL Viewer

When you open symbols from compiled assemblies, you can always study them in the intermediate language independently of their presentation in the editor. Even if the symbol is displayed in the original source file obtained through PDB, ReSharper will find the related piece of IL code for it.

View intermediate language (IL) for a decompiled symbol

  1. Choose ReSharper | Windows | IL Viewer in the main menu.
  2. If you are in decompiled code, you can also invoke the Navigate To Ctrl+Shift+Gand choose IL Code.
  3. By default, while the window is open the IL view is synchronized with the caret position in the code viewer and matching code is highlighted. To change that, clickTrack Caret in Editor  on the toolbar of the IL Viewer.

In the IL Viewer window, you can learn descriptions of IL instructions in tooltips when hovering the mouse over an instruction. The descriptions are taken from MSDN and from the ECMA-335 standard (Partition III: CIL Instruction Set).

When you set the caret at a code symbol or instruction, all usages of this item are highlighted. Loops in your code can be distinguished by corresponding indents and comments.

Visual Dependency Analysis

With ReSharper, you can build and analyze dependency graphs of types and projects in your solution. All visual graphs are built without compiling anything and conveniently laid out by default. Right on the graphs, you can invoke a lot of other ReSharper features includingnavigationrefactorings, and more.

Explore Type Dependency Diagram

ReSharper | Architecture | Show Type Dependency Diagram
ReSharper_ShowTypesDependencies

ReSharper allows you to visually study how types depend on each other in your solution. In the type dependency diagram, you can add any number of types from different projects or compiled assemblies and visualize different kinds of dependencies between them.

Build the initial diagram

There are several ways to build a new type dependency diagram:

  • Select one or more items in the Solution Explorer, Object Browser, Architecture Explorer, Class View, or Assembly Explorer window and then choose ReSharper | Architecture | Show Type Dependency Diagram in the main menu, right-click the selection, and choose Show Type Dependency Diagram, or alternatively, press Ctrl+Shift+Alt+A and then choose Show Type Dependency Diagram
    In this case, all types declared within the selected items are added to the diagram, and aggregation, usage, and inheritance dependencies are visualized.
  • Set the caret anywhere in the editor, and choose ReSharper | Architecture | Show Type Dependency Diagram in the main menu or invoke the Inspect This command ( chooseReSharper | Inspect | Inspect This or press Ctrl+Shift+Alt+A), and then choose Show Type Dependency Diagram
    In this case, all types from the file are added to the diagram, and aggregation, usage, and inheritance dependencies are visualized.
  • In the Architecture View, select one or more items, right-click the selection and choose Show Type Dependency Diagram in the context menu.
  • In the result list of the Go to Base Symbols, Go to Derived Symbols, Navigate To Exposing APIsor similar commands, press Alt+Num+ or click Show on Diagram   
    In case of base/derived symbols, the corresponding part of the inheritance hierarchy is added to the diagram and only inheritance dependencies are visualized. In case of the exposing APIs, the diagram displays types containing methods that return the given type and only return typedependencies.
  • For the list of results shown in the Find Results window or Hierarchy window, click Show on Diagram 
    In these cases, all usages or hierarchy entries are added to the diagram, and usage/inheritancedependencies are visualized.
  • Select one or more project references, right-click the selection, and choose Show Usages on Diagram 
    In this case, usages the diagram will show usages of types from the referenced assembly in the referencing project.

The newly created project dependency diagram is displayed in a new tab of the Hierarchy window.

Note that the diagram is not synchronized with the solution, that is if you rename or delete types in your code, the diagram is not changed. To see whether the diagram is up to date, you can check the creation time displayed in the bottom right corner. You can also rebuild the diagram by clicking Refresh Type Dependencies   on the toolbar.

Adjust the view of the diagram

Type dependency diagram can be laid out in two ways:

  • Inheritance Hierarchy Layouter— this option arranges types according to their inheritance relations: the base types are moved upward.
  • Business Logic Layouter— this option arranges types according to all displayed relations between them.

You can switch between these options using the corresponding selector in the left:

Diagram layout is updated automatically every time you refresh the diagram, add or remove types, or change dependency filters.

To pan and zoom the diagram, use the controls in the upper left corner of the diagram area. Alternatively, you can click anywhere in the diagram area outside the diagram items and drag while the hand cursor   is shown. For zooming, you can also use the mouse wheel.

The diagram layout is calculated automatically, but you can change it if necessary: all items can be moved. To move an item (a type, a dependency link, or a grouping item), first click it to select, and then click and drag it while the cross cursor   is shown.

If necessary, you can collapse and expand grouping items in the diagram in one of the following ways:

  • Click the down arrow in the left top corner of the grouping item. When collapsed, the sign changes into an up arrow and you can click it to expand the item.
  • Select a grouping item in the diagram and press Ctrl + Left Arrow and Ctrl + Right Arrow.

Add and remove items on the diagram

At any moment, you can modify the displayed diagram so that only desired types are displayed. If necessary, you can reverse changes made in the diagram (added/removed items) step by step by clicking Undo   or pressing Ctrl+Z. To reverse the Undo commands, click Redo   or pressCtrl+Y.

When your focus is anywhere in the diagram area, you can start typing to find and add types from the entire solution.

To remove types and folders from the diagram, either use the cross in the right top corner of grouping items or press Delete while the items are selected. Alternatively, select items you want to keep, right-click the selection and choose Show Only Selected Items in the context menu. For multiple selection, Ctrl-click items.

There are also several ways to add items to the diagram:

  • Drag-n-drop types, folders, and projects from the Solution Explorer to the diagram.
  • Select a type in the editor and drag-n-drop the selected type to the diagram.
  • To find and add all referenced types, right-click a type or a grouping item and choose Add all referenced types in the context menu. If you invoke this command on a grouping item (folder or project), ReSharper adds referenced types for all types that are currently shown.
  • To find and add types by name from the solution and referenced assemblies, start typing the name in the search box. You can use wildcards (for example the asterisk *) and CamelHumps while typing:

Select a type and press Enter or click it to add it to the diagram. Types highlighted with green in the drop-down are already added to the diagram. If you select such type, the diagram focus moves to it.

  • In the details popup, click any related type to add it, or use the Add all used types to the diagramAdd all usages to the diagramAdd all base types, and Add all immediate inheritors links to add multiple types.

To speed up laying out the diagram, disable all dependency filters before you add a lot of new types to the diagram or expand a large grouping node, and then enable the necessary filters again.

Study specific types and containers

When a node is collapsed, you can hover a mouse over it and quickly check out what is inside. In the popup that appears, you can see the number of types added to the diagram within this node and all modules referenced from within this node:

If necessary, you can click referenced modules and/or click Add missing items to add other items from this node to the diagram.

You can double-click any type to open it in the editor. If the type is defined in a compiled assembly, it is opened according to your preferred way of navigating to compiled code.

You can get the detailed information on any specific type (as well as on any dependency between types). To get details of a type, hover the mouse over it, and as soon as the details popup appears, move the mouse pointer on it.

On the type details popup, you will see which types the given types uses, where the type is used, inherited types, types use in constructor parameters and more. 
If the type has XML documentation, the summary is also displayed on the popup.

You can click types to add them to the diagram. Types highlighted with green are already added to the diagram. If you click such type, the diagram focus moves to it. The Go to declaration link in the top upper corner allows you to open the type in the editor.

Study dependencies between types

On the type dependency diagram, you can visualize several kinds of dependencies. To show or hide specific kinds of dependencies, use the corresponding items in the Filter Dependencies  selector:

  • Aggregation Dependencies— displays a kind of dependency when a type is a collection or container of other types, 
    This kind of dependency is shown as a green dotted line. Name of the corresponding field is shown next to the line. You can hover the mouse over this line to see the field declaration and navigate to the corresponding place in the editor.
  • Usages Dependencies— displays a kind of dependency when variables, parameters or method returns of one type are used in another type. 
    This kind of dependency is shown as a blue line whose thickness reflects a relative number of usages. You can hover the mouse over this line to see the list of usages:

Clicking on specific usages will bring you to the corresponding place in the text editor, clicking on the Show all usages link opens all usages in the Find Results window.

  • Inheritance Dependencies— displays a kind of dependency when one type extends or implements another type. This kind of dependency is shown as a grey line. You can hover the mouse over this line to see the inheritance relation and navigate to the corresponding place in the editor. 
    Transitive inheritance dependencies are shown using dashed lines. You can hover the mouse over such lines and use the popup to check the types though which the dependency goes and add these types to the diagram by clicking on them.

  • Return Type Dependencies— displays a kind of dependency when one type has methods or properties that return another type. This kind of dependency is shown as a violet line. You can hover the mouse over this line to see the list of members and navigate to the corresponding places in the editor.
  • Constructor Injection— displays a kind of dependency when one type is exposed as a constructor parameter of another type. This kind of dependency is shown as a brown line. You can hover the mouse over this line to see the constructors and navigate to the corresponding places in the editor.

Invoke other ReSharper features on the diagram

Navigate from items on the diagram

To list all available navigation destinations of any item in the Navigate To menu, pressCtrl+Shift+G or right-click the item and choose Navigate To.

You can locate any item (file, folder, or project) in the Solution Explorer by pressing Alt+Shift+Lwhen the item is selected.

You can also list related usages by clicking Show all used types in find results window or Show all usages in find results window in the details popup of a type or Show all usages in the popup of a dependency link.

Refactor items on the diagram

From any item on the diagram, you can invoke all available refactorings. To do so, pressCtrl+Shift+R or right-click and choose Refactor This.

You can also perform the Move to Folder refactoring by dragging a type to the desired folder. This refactoring would move the file containing the type to the target folder, fix namespace references and change internal visibility to public if necessary. 
Note that by default, this behavior is enabled. To disable it, click Allow 'Move to Folder' on drag-n-drop  .

Note that after the drag-n-drop refactoring, the diagram is updated automatically, but other refactorings that you invoke from the Refactor This menu do not update the diagram; you will need to click Refresh Type Dependencies   on the diagram's toolbar.

Export the diagram to a file

At any point of exploring dependencies, you can use the following toolbar buttons to export the diagram to a file:

  • Export to PNG  to export the current view of the diagram to a PNG image.
  • Export to GraphML   to export the diagram in the GraphML format for external analysis.
  • Export to XPS   to export the diagram in the XPS format if you need to print a large diagram.

Explore Project Dependency Diagram

ReSharper | Architecture | Show Project Dependency Diagram 
ReSharper_ShowProjectDependencyGraph

With ReSharper, you can explore project dependencies in your solution having a visual presentation of the solution architecture.

The Architecture View opens in a new editor tab and allows visually exploring project dependencies and comparing the current state of the solution to snapshots taken earlier.

Right-click projects on the diagram to use the same ReSharper project-level commands(including code inspection, navigation, refactoring, and unit testing) as those available in the context menu of solution nodes in the Solution Explorer.

Open project dependency diagram

If the coupling analysis is enabled, building the dependency diagram for large solutions can take some time. However, the analysis is performed asynchronously and without building the solution. So you can continue working with code while the diagram is being built.

  1. In the Solution Explorer, select one or several projects, one or several solution folders, or the solution node.
  2. Right-click the selection and choose Show Project Dependency Diagram or chooseReSharper | Architecture | Show Project Dependency Diagram in the main menu.
  3. The Architecture View. opens in a new document tab showing dependencies for the items that you selected initially.
  4. The initially selected items are also checked in the left part of the Architecture View, which lists all solution items. You can check other items: they will appear in the diagram and the corresponding links will be added.
  5. If necessary, you can change grouping of items using the Group by selector in the toolbar:
    • None - all projects are displayed without grouping.
    • Solution Folders - projects are grouped by solution folders.
    • File Structure - projects and solution folders are grouped by the file system structure.

Understand links between projects

ReSharper builds the diagram in two steps:

  1. Build the dependency diagram based on the project references.

This step is done automatically when you open the diagram and it takes almost no time even for large solutions.

  1. Perform the coupling analysis to calculate numbers of usages in the referencing project.

This step is resource-intensive and can take up to several minutes, but it runs in the background. The progress of the analysis is reflected by the status bar on top of the Architecture View.

The state of the coupling analysis corresponds to the state of the Enable Coupling Analysis  button. The coupling analysis is a resource-intensive process and may affect performance on large solutions. If you experience any lags when working with the diagram, you can use this button to disable the coupling analysis, adjust the diagram as needed, and then enable the analysis again. The analysis algorithm first calculates the coupling of the displayed projects and then processes projects hidden from the view.

Links between projects in the diagram can be displayed in the following ways:

Show and hide items

You can show or hide specific solution items (projects, folders, solution folders) in the diagram using check-boxes for the corresponding items in the left.

There are also several ways to show/hide items right from the diagram area:

  • To select some items in the diagram and hide others, Ctrl-click items you want to select, then right-click the selection and choose Selection | Show only selected modules.
  • To select two linked items, right-click the link between them and choose Selection | Show only selected modules.
  • To hide an item, you can select it in the diagram and press Delete.
  • Another way to concentrate on specific items is to display the dependent or referenced projects and hide all other items. To do so, select one or more items (projects or grouping items), right-click the selection and choose Show This/These and Dependent/Referenced. Note that these commands only hide the irrelevant items and do not add any referenced/dependent nodes, which are currently hidden.
  • To display all items referenced by or dependent on the specific projects, even if these items are currently hidden from the view, select one or more items and choose Selection | Add referenced/dependent modules.

If necessary, you can reverse changes made in the diagram (shown/hidden projects) step by step by clicking Undo   or pressing Ctrl+Z. To reverse the Undo commands, click Redo   or pressCtrl+Y.

Pan and zoom the diagram

To pan and zoom the diagram, use the controls in the upper left corner of the diagram area. Alternatively, you can pan the diagram using your touchpad, scroll bars or click anywhere in the diagram area outside the diagram items and drag while the hand cursor   is shown. You can also use the mouse wheel for zooming.

Rearrange items on the diagram

The diagram layout is calculated automatically, but you can change it if necessary: all items can be moved. To move an item, first click it to select, and then click and drag it while the cross cursor  is shown.

Group projects on the diagram

Using the Group by selector, you can group projects by solution folders or by file system structure. The grouping applies both in the left part and in the diagram.

If necessary, you can collapse and expand grouping items in the diagram in one of the following ways:

  • Click the down arrow in the left top corner of the grouping item. When collapsed, the sign changes into an up arrow and you can click it to expand the item.
  • Select a grouping item in the diagram and press Ctrl + Left Arrow and Ctrl + Right Arrow.
  • Click Collapse Graph   and Expand Graph   on the toolbar to collapse or expand all grouping items.

Analyze project references

To learn more about the usages of types from one project in another, select the corresponding link between the projects and press Alt+F7 or right-click and choose Show Usages. ReSharper will show the usages in the Find Results window.

If the coupling analysis is over for a specific reference and ReSharper highlights it as unused (with a dotted line), you do not need to switch from the diagram to remove the unused reference - just select it and press Ctrl+Shift+R or right-click and choose Refactor This. Then pressAlt+Delete or click Safe Delete Assembly Reference.

Detect possible architecture problems

If you are trying to follow the best practices in solution architecture, your application probably has the layered structure with separate layers that communicate with each other.

The Show possible paths   button allows you to find out whether the application layers are designed correctly, not only in terms of grouping, but also in terms of communications between the layers. In short, when the button is on, you can see whether two specific projects have a path between them consisting of other referenced projects that are currently hidden from the view. These paths are shown in green dotted lines. The button is only enabled if there are hidden intermediary projects that would link any two of the currently displayed projects.

To illustrate the way it works, consider the following example:

  1. Imagine that we have a large solution and are now analyzing the 'Services' architecture layer which is represented by the corresponding solution folder. We show the two projects that we are interested in, others are hidden:

 

  1. The two projects do not have direct project references between them, however, if we enable theShow possible paths   button, we'll see that there is a path between these projects through other projects:

 

  1. To see how these two projects can depend on each other, we right-right on the path link and choose Show path. The intermediary projects appear on the diagram, and we can see that they all are in another layer:

 

Based on this information, we can see that the application structure may need to be reworked.

Export the diagram to a file

At any point of exploring dependencies, you can use the following toolbar buttons to export the diagram to a file:

  • Export to PNG  to export the current view of the diagram to a PNG image.
  • Export to GraphML   to export the diagram in the GraphML format for external analysis.
  • Export to XPS   to export the diagram in the XPS format if you need to print a large diagram.

Compare saved snapshots to the current solution state

At any time you can save a snapshot of the current state of your solution to a file and use it for future references. To do so, click Save Architecture Graph  on the toolbar and then choose where to save the snapshot file.

The proprietary file format of the diagram snapshots .argr can be also used with JetBrains Rider.

You can load and study saved snapshots later by choosing ReSharper | Architecture | Compare With Saved... in the main menu and selecting a diagram snapshot file .argr
The snapshot will open in a new editor tab and you will be able to see differences between the current state of the solution and the state saved in the snapshot.

If the dependency diagram was opened from file, the Show Diff   button becomes available and toggled on by default. You can use this button to show or hide the differences between the snapshot and the current solution state.

///

本文标签: CodeAnalysis