JetBrains ReSharper Reviewer's Guide
This document showcases the capabilities of JetBrains ReSharper software product as of version 4.1 for the purpose of convenient evaluation by reviewers.
What is ReSharper
JetBrains ReSharper is a productivity add-in to Microsoft Visual Studio that, by extending native Visual Studio functionality, facilitates professional development using C#, VB.NET, XML, XAML, build scripts, and unit tests.
See Appendix. ReSharper 4 vs Visual Studio 2008 for the list of specific enhancements provided by ReSharper compared to Visual Studio functionality.
JetBrains ReSharper enhances .NET developer experience in multiple ways to make sure that developers are able to perform various important tasks, including the following:
- Save time on compilation, locating and fixing errors
ReSharper instantly detects and highlights errors in C# code, without having to compile it first
ReSharper provides corrections for most errors, helping solve any problems instantly (see Code Analysis)
- Automate routine tasks
Quickly create methods, properties, variables or classes from their usages
Easily generate constructors, properties, delegating and equality members; implement and override members (see Code Generation)
Smart templates help quickly insert frequently used code constructs (see Templates)
Complete Statement inserts necessary syntax elements and gets you in position to start writing the next statement (see Coding Assistance)
- Get useful hints when necessary
Parameter Info and three types of Code Completion are way more useful and versatile with ReSharper
Suggestions in completion lists are filtered based on the expected type of an expression
Required namespaces are imported instantly, right from where you type
Quick Documentation provides comprehensive info on any class or method in a pop-up window, with clickable links to external resources (see Coding Assistance)
- Improve coding practices
Changes are made easy with 34 solution-wide, cross-language automated refactorings (nearly 5 times as many as in Visual Studio 2008) (see Refactorings)
ReSharper's 130+ automated code transformations (context actions) enable quick local modifications (see Coding Assistance)
Comprehensive Code Cleanup reformats code, removes redundancies, enforces customizable conventions, and more (see Code Cleanup)
- Navigate to any corner of a solution
Dozens of smart navigation and search features bring the whole solution at developer's fingertips
Type Hierarchy, File Structure, and other features make the structure of solution items clearer (see Navigation and Search)
- Handle multi-language solutions with ease
Refactorings, navigation and search, and coding assistance work across C#, VB.NET, XAML, ASP.NET (see Cross-language Functionality)
Supported Languages and Technologies
ReSharper 4 Full Edition supports the following languages/technologies on a full or limited basis:
- C# (up to 3.0)
- VB.NET (up to VB8)
- ASP.NET (up to 3.5 SP1)
- NAnt and MS Build scripts
See ReSharper 4 Feature Map for details.
Most examples in this guide are based on C# code.
|Processor||Pentium IV 1.5 GHz (Intel Core 2 Duo 2GHz recommended)|
|Memory||1Gb (4Gb recommended)|
|Disk space||100 Mb|
|Operating System||Microsoft Windows 2000/XP/Vista/7(incl.64-bit)|
|Software installed||Microsoft Visual Studio 2005 with Service Pack 1 or Microsoft Visual Studio 2008
(Note: ReSharper doesn't work under Microsoft Visual Studio Express)
Downloading and Installing ReSharper
See installation instructions at the ReSharper website if necessary.
Choosing a Keyboard Layout
When you start Visual Studio for the first time after installing ReSharper, a dialog box called ReSharper Keyboard Scheme displays, where you're supposed to choose a keyboard layout, or opt to avoid setting any shortcuts at all. The following guidelines assume that you have chosen the Visual Studio keyboard layout.
See ReSharper 4 Default Keymap: Visual Studio scheme (PDF) and ReSharper 4 Default Keymap: ReSharper 2.x / IDEA scheme (PDF) for detailed listings of shortcuts provided by the two alternative layouts. At any time, you can switch between keyboard layouts using the ReSharper | Options | Environment | General tab.
You can configure almost every ReSharper setting using the ReSharper Options dialog box. To access the dialog box, open the ReSharper menu and choose Options:
Navigate the left pane to access different tabs with classified settings.
Only fonts and colors used for ReSharper highlighting are configured outside of the ReSharper Options dialog box. To view or modify fonts and colors, choose Tools | Options | Environment | Fonts and colors (all ReSharper items in the Display items list box have ReSharper prefix).
Note: If you're using ReSharper in a large solution and you experience slight delays when typing code, choose ReSharper | Options | Environment | IntelliSense | Completion Behavior and increase the value in the Automatically show completion list in... milliseconds after: box by 100-200 milliseconds. In most cases, doing so solves the issue.
Code Analysis for C#
What is Code Analysis
The code analysis feature in ReSharper provides the following advantages:
- ReSharper executes continuous, on-the-fly inspection of C# code for errors and inefficiencies in the current file. That means you don't have to compile your code just to find out what compilation errors it contains.
- When ReSharper analyzes code, it executes a wide set of inspections. In addition to compiler
this set includes more than 100 inspections related to code redundancies, bad practices and potential errors,
such as "Function never returns", "Unused type parameter", "Redundant using directive", "Assignment is not used"
etc. ReSharper assigns to these inspections four severity levels — errors, warnings,
hints — and highlights them in code in different ways:
- Errors have the highest priority of all - they prevent your code from compiling. Errors
highlighted in red:
or emphasized with a red curly underline:
- Warnings warn you of coding inefficiencies or potential errors (redundant type casts or
import directives, incorrect format strings, unused private methods, etc.). Code that has associated
warnings is emphasized with either grayed text:
or a blue curly underline:
- Suggestions provide insights into code structure, drawing your attention to things that
useful to know. Suggestions are highlighted by green curly underline:
- Hints bring your attention to particular code details and recommend ways of
items that have associated hints are highlighted with a solid green underline:
- Errors have the highest priority of all - they prevent your code from compiling. Errors are highlighted in red:
- You can instantly see whether the current file contains any errors, warnings, or suggestions, by looking at the
Marker Bar that ReSharper adds to the right-hand side of the editor window:
The Status Indicator at the top turns red if the file contains at least a single error, yellow if it contains warnings, or green if the file is clean. When you hover over the Status Indicator, it shows the total number of errors and warnings in the current file.
- Quick-fixes are predefined operations that ReSharper provides to take action upon errors, warnings, suggestions, and hints. Quick-fixes are described in a separate subsection below.
- Code analysis works not only in regular C# classes, but also in C# code in ASP.NET markup and code-behind. In addition, ReSharper provides a compact set of inspections for build scripts, XML, and XAML.
Navigating between Code Highlights
You can easily navigate between errors, warnings and suggestions in your code using two techniques:
- By clicking individual markers in the Marker Bar
- Using shortcuts:
- Shift+Alt+Pgdn to go to the next error
- Shift+Alt+Pgup to go to the previous error
- Alt+Pgdn to go to the next error, warning or suggestion
- Alt+Pgup to go to the previous error, warning or suggestion
Quick-fixes provide a way to instantly repair any piece of code that ReSharper highlights as error, warning, suggestion, or hint. In other words, a quick-fix represents what you can do in order to make code free of ReSharper inspection highlights.
Quick-fixes are represented by the red light bulb that appears automatically to the left of a highlighted code line, when you position the caret on the highlight. Note that ReSharper also provides yellow bulbs, representing context actions that serve a slightly different purpose (see details below).
To display the list of available quick-fixes for a given highlight, press Alt+Enter. Then simply select an appropriate quick-fix from the list, and it will correct your code automatically:
Overall, with more than 100 inspections, ReSharper provides about 200 quick-fixes. That is, for almost every problem in code, ReSharper is able to suggest a number of possible solutions.
You can switch on the solution-wide code analysis feature to view errors in all solution files in a separate tool window:
It shows not only errors and inefficiencies that are discovered in individual files, but also problems that arise due to cross-referencing code between assemblies (for example, wrong member visibility). Watch the circle icon on the right-hand side of the status bar, which serves as the Solution-Wide Analysis status indicator:
By default, Solution-Wide Analysis is disabled, and the circle icon turns gray. To turn it on, just double-click the circle icon.
ReSharper offers a variety of coding assistance features to save developer's time and increase productivity in a number of ways, including:
- Extended IntelliSense: Code Completion, Complete Statement, Parameter Info
- Local code transformations (context actions)
- Highlighting features: syntax highlighting, highlighting matching delimiters
- Auto-importing namespaces
- Quick documentation
- Text manipulation features: Extend/Shrink Selection, Duplicate Line or Selection, Comment/Uncomment Code, Move Code etc
- Auto-inserting delimiters (brackets, parenthesis and quotes)
ReSharper provides 3 types of Code Completion:
- Symbol Completion (Ctrl+Space) completes names of classes, methods, variables, keywords, and any other symbols that are available within the current visibility scope (including extension methods that were previously imported)
- Smart Completion (Ctrl+Alt+Space) filters the list of types, methods, and variables to match the expected type of an expression. It works anywhere as long as ReSharper can determine the expected type of the expression, for example, right-hand sides of assignments, variable initializers, or return statements
- Import Symbol Completion (Shift+Alt+Space) displays all types that match a given prefix regardless of what namespace they belong to. It automatically inserts appropriate namespace import directives to the current file if a selected type was not imported previously. It also works after dot with extension methods
ReSharper Code Completion features extend and improve Visual Studio's native IntelliSense with a variety of facilities, including (but not limited to) the following:
- As you start to type, completion list is narrowed down to match the specified prefix
- Immediate members of a type are emphasized with bold font, as opposed to inherited members
- All overloads for a member are displayed in a signature pop-up and you can
- Where applicable, Code Completion suggests indexer along with type members, and corrects expression syntax accordingly if it's selected
- Custom icons for parameters and local variables are provided to distinguish them from fields
- Support for CamelHumps means that you can complete a long type name by entering only its uppercase characters — for example, DRFB instead of DecoderReplacementFallbackBuffer
- When you declare a field, method parameter, or local variable, ReSharper can suggest a list of possible names to choose from, taking into account your defined naming conventions (you can configure them by choosing ReSharper | Options | Languages | Common | Naming Style)
You can configure the look and feel of code completion by choosing ReSharper | Options | Environment | IntelliSense | Completion Behavior or ReSharper | Options | Environment | IntelliSense | Completion Appearance.
Complete Statement (Ctrl+Shift+Enter) inserts necessary syntax elements (braces, semicolons etc.) and gets you to the position to start the next statement, saving you from excessive juggling with the caret. In a sense, it's a hybrid of two ReSharper features: Code Completion and Auto-inserting Delimiters.
Complete Statement comes to rescue in numerous scenarios, including auto-closing parentheses, adding semicolons, completing if, while and for statements, and so on. For example, whenever you declare a new method, Complete Statement comes handy after specifying method parameters:
If you press Ctrl+Shift+Enter at this point, ReSharper will automatically insert a closing parenthesis, as well as both braces, and put the caret right where you can proceed with writing the method body:
See Complete Statement Scenarios at JetBrains .NET Tools Blog for other ways of using this feature.
Context actions are intended for enforcing coding guidelines (for example, field or variable declaration and initialization being on the same line), minor code transformations (for example, converting switch to if-else constructs), and small code inconsistencies (such as excessive brackets in the if condition). Context actions represent what you may want to do in a certain context — as opposed to quick-fixes that let you make essential corrections. Sometimes context actions are compared to refactorings, but they are executed on a much less global scale.
ReSharper automatically indicates when one or more context actions are available at the current caret position with the yellow light bulb to the left of the code line.
Context actions are applied just like quick-fixes: you can either click the bulb or press Alt+Enter, and then select an appropriate action.
ReSharper provides triple digits of multi-task context actions for C#, VB.NET, and XML. For example, context actions for C# 3.0 include:
- Convert anonymous method to lambda
- Convert lambda to anonymous delegate
- Convert LINQ to method chain
- Initialize auto property from constructor parameter
- Inline method body as lambda
- Merge partial method declarations
- Replace 'var' with explicit type declaration
- Use collection initializer
- Use object initializer
You can view, enable or disable specific context actions by choosing:
- ReSharper | Options | Languages | C# | Context Actions for C#
- ReSharper | Options | Languages | Visual Basic .NET | Context Actions for VB.NET
- ReSharper | Options | Languages | XML | Context Actions for XML
ReSharper extends the default highlighting support of Visual Studio with highlighting for fields, local variables, types, and more, in both C# and VB.NET. For example, this feature allows you to easily distinguish between local variables and fields in your code. You can customize colors and fonts that ReSharper will use to highlight syntax of supported languages by choosing Tools | Options | Environment | Fonts and colors (all ReSharper items in the Display items list box have ReSharper prefix).
This part of Visual Studio's IntelliSense is also extended in ReSharper. When you call a method (procedure), Parameter Info shows all available method signatures and parameters at once, with relevant documentation (the tooltip appears automatically while you type, or you can display it by pressing Ctrl+Shift+Space). While you are adding new arguments, ReSharper grays out any signatures that become incompatible.
You can configure how this feature behaves by choosing ReSharper | Options | Environment | IntelliSense | Parameter Info.
To see the documentation for a certain class, method/function or other symbol right in the editor, position the caret on the symbol name and press Ctrl+Shift+F1. Documentation shows in a pop-up window with clickable links to other resources.
When a type name cannot be resolved because you forgot to issue the corresponding namespace import directive in the source code, a small pop-up appears to suggest one or more types to import. Simply press Alt+Enter, and the appropriate namespace import directive will be inserted automatically, and you won't lose your current caret position:
If for some reason you didn't react to the pop-up, you can import the namespace at any time by positioning the caret at the symbol, pressing Alt+Enter and choosing an appropriate quick-fix:
When you type (, [, ", or ' in the editor, a pair character is inserted automatically (whenever appropriate). If you change your mind and press Backspace to delete an opening delimiter, its closing pair will also be deleted. Of course, if the closing parenthesis or quote already exists, ReSharper will not add the second one.
You can configure how this feature works by choosing ReSharper | Options | Environment | Editor.
Complete Statement solves a similar kind of problem in the context of code completion.
Highlighting Matching Delimiters
In C#, whenever you place the caret immediately before/after a closing parenthesis/bracket/brace, the matching opening character is highlighted with color or outline, and vice versa. The same applies to Sub/End Sub or Function/End Function in VB.NET, as well as to tags in XML.
If a matching piece of code scrolls off the screen, an appropriate pop-up appears for your convenience:
You can configure this feature by choosing ReSharper | Options | Environment | Editor.
The Extend Selection feature helps successively select expanding blocks of code. That is, you can easily select any expression in the code by placing the caret somewhere inside it and pressing Ctrl+Alt+Right a few times:
Shrink Selection works in the opposite way and can be applied by pressing Ctrl+Alt+Left.
See Extend/Shrink Selection at JetBrains .NET Tools Blog for details on this feature.
Duplicate Line or Selection
You can quickly duplicate any line (block) of code by placing the caret at this line in the editor (or, respectively, selecting the desired block) and pressing Ctrl+D. This is especially useful with similar method calls or XML tags.
Moving Code Elements
You can quickly change the order of code elements with four shortcuts:
- Ctrl+Shift+Alt+Up to move a code item up
- Ctrl+Shift+Alt+Down to move a code item down
- Ctrl+Shift+Alt+Left to move a code item left
- Ctrl+Shift+Alt+Right to move a code item right
In particular, this lets you:
- Move members up and down
- Reorder method parameters
- Move statements within a block
- Move statements out of or into a block
- Move XML tags up and down
- Move XML attributes left and right
Commenting and Uncommenting Code
Promptly comment or uncomment any block of C# or VB.NET code by selecting it in the editor and pressing Ctrl+Alt+/ (for line comment) or Ctrl+Shift+/ (for block comment in C#).
You can also use Ctrl+Alt+/ to quickly comment or uncomment the line of code where the caret is located in the editor if no block of code has been selected. In the same circumstances, pressing Ctrl+Shift+/ inserts the opening block comment (/*) and the closing block comment (*/) immediately before and immediately after the caret position, or removes them if the caret is positioned inside the commented code block.
You can also use this feature to insert comments in XML and XAML files.
Navigation and Search
Navigation and search features in ReSharper include:
- Commands and pop-up menus that help quickly go to different kinds of code symbols: "Go to" commands, Navigate from Here
- Specialized tool windows: Find Usages, File Structure, Type Hierarchy, To-do Explorer, Stack Trace Explorer
- Highlighting features: Highlight Usages, Highlight Current Line
- Drop-down lists showing coding history: Recent Edits, Recent Files
"Go to" Commands
ReSharper provides 3 groups of "go to" navigation commands that can be all accessed from the ReSharper | Go to menu.
Group 1: Navigate from anywhere. All commands in this group are available in respective pop-up windows, support search by capital letters in compound names (CamelHumps) and using wildcards (* represents zero or more characters, and ? represents one or more characters):
- Go to Symbol (Shift+Alt+T) allows solution-wide search by name for any
- Go to Type (Ctrl+T) navigates to any type in solution
- Go to File (Ctrl+Shift+T) navigates to any file in solution
- Go to File Member (Alt+\) navigates to a particular method or field in the current file
Group 2: Navigate from occurrence of a specific symbol:
- Go to Declaration (F12) navigates to the declaration of an item at the
caret position (letting you choose a declaration in partial classes):
- Go to Type Declaration (Ctrl+Shift+F11) navigates to the declaration of a type that a variable, field, or parameter under the caret belongs to
- Go to Base (Alt+Home) navigates to base type or method from a usage or
declaration of a type or method. In addition, special icons in the left gutter of the text
editor let you see when a method overrides, implements, or hides another method. Click the icon to navigate up
- Go to Inheritor (Alt+End) navigates down to a type or method that is derived from the current type or method
- Go to Usages (Shift+Alt+F12) navigates to usages of a symbol under the caret. This command is convenient when a symbol has few usages. In other cases, Find Usages is the preferable way of usage search.
Navigate from Here is used as a shortcut for all commands from this group.
Group 3: Navigate from anywhere within a member:
- Go to Next Member/Tag (Alt+Down) navigates to the next file member in C# or VB.NET, or to the next tag in XML or XAML
- Go to Previous Member/Tag (Alt+Up) gets you to the previous member or tag
- Go to Containing Declaration (Ctrl+[) goes to a method declaration from within its body, or to the containing class from a method declaration
In addition, Go to Last Edit Location (Ctrl+Shift+Backspace) navigates to the point of the most recent code modification.
The Find Usages feature quickly locates usages of any symbol in solution. Position the caret on any occurrence of the symbol for which you want to find usages and press Shift+F12. In mixed-language solutions, ReSharper 4 Full Edition enables searching for usages across multiple languages.
Search results are displayed in the Find Results window, where you can directly navigate to any usage. In addition, Find Results lets you preview source code where usages occur, filter them by type (read or write usages, invocation usages, attribute usages, or usages in documentation), group usages by categories, and view tabs with recent usage searches.
To specify the exact search scope (project, solution, solution and libraries, or current) and the type of usages to be found (usages of members, derived types, textual occurrences etc.), use the Find Usages Advanced feature (Ctrl+Shift+Alt+F12).
To highlight all usages of a symbol in the current file, position the caret on any single usage of this symbol and press Shift+Alt+F11. To cancel highlighting, press Esc. Read and write accesses are highlighted in different colors. In addition, highlighted usages appear in the Marker Bar.
With the File Structure window, you can see what members or elements your current code or markup file contains, and navigate directly to their declarations — just press Ctrl+Alt+F.
File Structure also displays regions defined in the current file and allows you to arrange declarations within classes and regions — just click and drag a node to its new location.
In addition, you can surround nodes with regions, and easily delete existing regions. To create a new region, select one or several nodes (they don't even have to be adjacent) and click the button in File Structure toolbar.
With ReSharper, you can view the inheritance hierarchy of any type in a dedicated window. The Type Hierarchy window shows both base types and inheritors of the selected type and allows you to navigate to any of them with a single click. For any node in the hierarchy, you can view all or only polymorphic members in a separate preview pane.
To open the Type Hierarchy window for a type, position the caret at any type usage, and press Ctrl+Alt+H.
Navigate from Here
Navigate from here (Alt+') is a drop-down list that shows all navigation options available at the current caret position. It serves as a shortcut for other ReSharper navigation commands (Go to Usages, Go to Declaration, Go to Base etc.), but adds a number of original destinations.
Particularly, Navigate from Here lets you navigate from the symbol under caret to:
- Declaration of the symbol
- Usages of the symbol
- Type declaration
- Base class declaration
- Control flow target
- Function exit(s)
- Implementing members
- Overriding members
- Conflicting declarations
- Member overloads
- To-do Explorer
- Unit Test Explorer
See Navigate from Here at JetBrains .NET Tools Blog for comprehensive overview of this feature.
ReSharper keeps track of to-do items in solution using 4 default patterns: Todo (searches for "todo" word in comments), Note ("note" in comments), Bug ("bug" in comments), and Not Implemented (NotImplementedException type usages in code). ReSharper collects to-do items according to these patterns and shows them in To-do Explorer (Ctrl+Alt+D). You can configure your own custom patterns in the ReSharper | Options | Tools | To-do Items tab.
Stack Trace Explorer
When you receive an external stack trace (for example, from a bug report), you can copy-paste it into Stack Trace Explorer to navigate to where an exception originated in the source code. The lines within the stack trace will be represented as hyperlinks. To open the Stack Trace Explorer, press Ctrl+E,T.
Pressing Ctrl+, opens a pop-up window with the list of recently opened files, where you can select any item to navigate to.
This feature (Ctrl+Shift+,) works a lot like Recent Files, but the pop-up window shows the list of files and symbols that you have recently modified.
Highlight Current Line
You can opt to highlight the line where the caret currently resides with a color.
To enable this feature, choose ReSharper | Options | Environment | General and select Highlight current line. To customize the color of highlighting, choose Tools | Options | Environment | Fonts and colors and modify the ReSharper Current Line display item.
Locate in Solution Explorer
Pressing Shift+Alt+L lets you highlight the currently opened file in Solution Explorer and auto-scroll to its entry.
ReSharper provides the following two groups of code generation features.
Generating Types and Type Members Based on Usage
With ReSharper, you can use a symbol (method/function, property, local or field variable or even a class) before it's been declared. ReSharper will suggest a quick-fix (for C#) or several context actions (for VB.NET) for declaring the corresponding symbol based on its usage, and then adjust the declaration according to the usage context. For example, if you create a method from usage, ReSharper will not only create a method, but also detect its return type and types of its parameters.
Generating Common Type Members
Using a special Generate drop-down menu (Alt+Ins), ReSharper makes it easy to generate different type members, including constructors, properties, formatting members (ToString() overrides), equality members (Equals() and GetHashCode() overrides) and delegating members, as well as to override members of base classes and implement missing members inherited from interfaces and abstract classes.
Additional options are provided in code generation dialog boxes, including:
- For all generated members: copying XML documentation
- For constructors and properties: customizable access rights
- For properties: read or read-write access, generating automatic properties, declaring properties as virtual
- For overriding and implementing members: wrapping in regions
- For implementing members: the ability to implement as public or virtual members, or provide explicit implementation
- For equality members: allowing or disallowing nullity of objects being compared, implementing IEquitable<T> interface
ReSharper provides the richest set of automated code refactorings for C# 3.0 and VB8 available in the Visual Studio ecosystem.
To view the list of refactorings available at the current caret position, press Ctrl+Shift+R. The Refactor This menu opens:
As an alternative, use ReSharper | Refactor menu, individual keyboard shortcuts (if available), or context menus in the text editor and ReSharper tool windows.
Each code refactoring analyzes the entire scope of the code selection to which it is applied (it can be as wide as your whole solution), including cross-language code, and uses this insight to update the code structure in the most intelligent way possible.
See ReSharper 4 Feature Map for details on availability of refactorings for different languages and technologies.
Note that ReSharper also provides a rich set of more straightforward local code transformations called context actions.
- Rename (Ctrl+R, R) allows you to rename any symbol, including namespaces, types, methods, parameters, local variables, properties, fields, and events. It automatically finds and corrects all references to the symbol being renamed, and suggests to rename related symbols (for example, read and write properties related to a field, or variables in a class being renamed). In addition, it optionally renames occurrences found in comments and string literals.
- Change Signature (Ctrl+R, S) allows you to modify a method signature
- Add, remove, rename, or reorder parameter(s)
- Change return type
- Change parameter type(s)
- Rename method
- Copy Type creates a copy of a type with a different name or within another namespace. ReSharper will take care of creating a separate file for it. All parts of partial types will be copied as well, even if they are located in separate files.
- Make Method/Property Non-Static (Non-Shared) converts a static method (Shared in VB.NET) to an instance method in the selected parameter's type (i.e. moves the method to parameter's type and transforms the parameter into 'this') and transforms method calls accordingly.
- Make Method/Property Static (Shared) converts a non-static method into a static one (Shared in VB.NET) by making 'this' a parameter of the method. After refactoring, the target method will be declared as static (Shared in VB.NET), and necessary parameters will be added to its call sites.
- Safe Delete (Ctrl+R, D or Alt+Del) lets you delete a type, type member, or any other symbol, along with all its usages. If necessary, ReSharper will show you usages that are unsafe to delete, allowing you to edit the corresponding code.
- Move Static Member (Ctrl+R, O) moves static fields and methods to another type. To move non-static methods, perform the following sequence of refactorings: Make Method Static -> Make Method Non-Static, with the move happening in the latter.
- Move Type to Another File or Namespace (Ctrl+R, O) helps move types between namespaces and update references accordingly. You can also move a type to outer or nested scope or to another file.
- Move Type to Outer Scope (Ctrl+R, O) moves an inner type to an upper level. In case that the inner type uses members of the enclosing type, a reference to the enclosing type is passed as an argument to constructors of the moved type.
- Convert Abstract Class to Interface. Converting an abstract class to an interface is especially useful when you want a class to inherit from more than one abstract class, and you need to convert one of them to an interface.
- Convert Interface to Abstract Class. Before performing the conversion, this refactoring checks for any conflicts, i.e. for types implementing the interface that already have base type (which is an error in C# where multiple inheritance is disallowed).
- Convert Anonymous to Named Type (C# only) performs the conversion in the scope of either the current method (locally) or the whole solution (globally). In the dialog box that this refactoring provides, you can specify whether ReSharper should generate auto-properties or properties with backing fields, and also opt to generate equality and formatting method overloads.
- Convert Static to Extension Method (C# only). For the conversion to be carried out
static method must:
- have at least one argument
- reside in a static class
- Convert Extension Method to Plain Static (C# only) works in dialogless mode. The reverse functionality is provided by 'Convert Static to Extension Method'.
- Convert Property to Auto-Property (C# only) converts traditional properties with backing private fields to auto-properties that were introduced in C# 3.0.
- Convert Method to Property helps convert:
- non-void methods without parameters to properties with read access
- void methods with exactly one parameter to properties with write access
- Convert Property to Method(s) converts:
- properties with read access to getter-type methods (non-void methods without parameters)
- properties with write access to setter-type methods (void methods with exactly one parameter)
- properties allowing both read and write access to pairs of getter- and setter-type methods
- Convert Indexer (Default Property) to Method works a lot like 'Convert Property to Method' but is applied to indexers (default properties in VB.NET). You can convert only getter, only setter, or both, to a method.
- Convert Method to Indexer (Default Property) works in dialogless mode, and you may have to apply it to two methods to generate both a getter and a setter in your indexer.
- Extract Class from Parameters creates a new class or struct and converts parameters of the selected method into encapsulated fields of the newly created type (with constructor taking parameters, fields to store values and properties to retrieve values). Usages of parameters are converted to usages of properties of created type.
- Extract Interface helps create an interface from a class and make that class implement the created interface. You can choose the members to extract to the interface and specify a name for the interface.
- Extract Method (Ctrl+R, M) transforms a selected block of code into a method (Sub or Function in VB.NET). ReSharper will automatically analyze the code to detect the return value and/or out/ref parameters.
- Extract Superclass, when applied to a class declaration, helps create a base class and move some members to it.
- Inline Method (Ctrl+R, I) transfers a method's body into the body of its callers and remove the method altogether (whenever possible). The reverse functionality is provided by 'Extract Method'.
- Inline Variable (Ctrl+R, I) substitutes all occurrences of a selected variable or constant with its initializer. The reverse functionality is provided by 'Introduce Variable'.
- Introduce Field (Ctrl+R, F) creates a new field or constant and initializes it with the initializer of a selected expression or local variable.
- Introduce Parameter (Ctrl+R, P) creates a new parameter from a selected expression or local variable in a method. All call sites will be updated to reflect the changed signature, while maintaining the logic and the semantics. If the selected expression uses local variables that are inaccessible at call site, this refactoring allows to pass them as delegates.
- Introduce Variable (Ctrl+R, V) declares a new implicitly or explicitly typed local variable and initializes it with a selected expression inside the member code. The original expression will be replaced with the name of the variable. Should there be multiple occurrences of the original expression in code, you will be given an option to replace all of them with the newly created variable.
- Pull Members Up helps generalize behavior by moving type members to a superclass or an interface. ReSharper analyzes all members in the current class and makes a list of members that you can pull up. Before completing the refactoring, ReSharper checks for possible conflicts, for example, whether the members that you are trying to move to a superclass will be accessible in the destination type.
- Push Members Down helps specialize behavior by moving type members to a subtype. ReSharper analyzes all members of the selected type and makes a list of members that you can push down. Before completing the refactoring, ReSharper checks for possible conflicts, for example, whether the members you are trying to push down will be accessible in the destination type.
- Use Base Type where Possible generalizes code by replacing particular type usages with references to base type or interface where possible, that is, where no members of the derived type are used.
- Encapsulate Field (Ctrl+R, E) allows you to quickly create an accessor property from an existing field. Usages of the field are automatically replaced with usages of the property. An apparent advantage of this refactoring is that you can disallow direct access to a field through the use of properties.
- Replace Constructor with Factory Method encapsulates a constructor with a static method that returns a new instance of a class, following the "Factory Method" pattern.
What is Code Cleanup?
The Code Cleanup feature in ReSharper (Ctrl+E,C) combines customizable code formatting with a set of other useful actions, including:
- Removing code redundancies (C#)
- Optimizing namespace import directives (C#, VB.NET)
- Reordering type members (C#)
- Migrating to C# 3.0
- Inserting a common header into files being cleaned up (C#)
For example, you can simply run Code Cleanup to remove code redundancies instead of navigating between individual warnings and fixing them one-by-one. Essentially, Code Cleanup lets you run a set of ReSharper quick-fixes that are safe to execute in batch mode.
The scope of Code Cleanup can be as wide as whole solution, or as narrow as a code selection worth a line or two. For example, to run Code Cleanup within the whole solution, right-click its entry in the Solution Explorer and choose Cleanup Code. Running Code Cleanup from the text editor works in the scope of the currently opened file.
Code Cleanup works based on a selected profile that defines a set of actions to execute. There are two default profiles — Full Cleanup and Reformat Code — that can be complemented by custom user profiles with different sets of actions.
When a user presses Ctrl+E,C, the Code Cleanup dialog box opens, with the list of existing profiles on the left and settings defined by a selected profile on the right:
Select an existing profile, or create a new profile by clicking Edit Profiles. When the ReSharper Options dialog box opens at the Code Cleanup tab, click Add and configure a new custom profile. After getting back to the Code Cleanup dialog box, select your new profile and click Run.
Fine-Tuning Code CleanupIn every profile, you set a combination of options, such as Arrange 'this' qualifier, Remove code redundancies, Update file header, Reformat code etc. Some of them are configured directly when you set up a profile, while others depend upon different ReSharper settings. The following table lists these settings that you can configure in the ReSharper | Options dialog box, and maps them to Code Cleanup options.
|Path to options||Code Cleanup settings|
|ReSharper | Options | Code Inspection | Inspection Severity||
Use auto-property, if possible (C#): Takes action upon "Use var keyword when possible" code
inspection item (converts a local variable to implicitly typed variable if its initializer type equals to
Make field read-only, if possible (C#): Takes action upon "Field can be made readonly" code inspection item
Remove code redundancies (C#): Takes action upon about 30 code redundancies that ReSharper is able to remove safely
|ReSharper | Options | Languages | C# | Formatting Style | Other | Other||Arrange 'this' qualifier (C#): Applies a value selected in the Force "this." qualifier for instance member drop-down list and removes redundant this. qualifiers|
|ReSharper | Options | Languages | Common | File Header Text||Update file header (C#): Inserts or updates file header that you can specify in this tab|
|ReSharper | Options | Languages | C# | Namespace Imports||Optimize 'using' directives (C#): Removes unused namespace import directives and implements
configured in this tab
Shorten qualified references (C#): Replaces fully qualified names with short names where possible by importing namespaces, implementing settings configured in this tab
|ReSharper | Options | Languages | Visual Basic .NET | Namespace Imports||Optimize 'import' directives (VB.NET): Removes unused namespace import directives and
settings configured in this tab
Shorten qualified references (VB.NET): Replaces fully qualified names with short names where possible by importing namespaces, and implements settings configured in this tab
|ReSharper | Options | Languages | C# | Formatting Style||Reformat code (C#): Reformats code according to options configurable in this group of tabs for C# code|
|ReSharper | Options | Languages | Visual Basic .NET | Formatting Style||Reformat code (VB.NET): Reformats code according to options configurable in this group of tabs for VB.NET code|
|ReSharper | Options | Languages | C# | Type Members Layout||Reorder type members (C#): Reorders type members according to a pattern configurable in this tab (see XML Schema for further reference)|
ReSharper templates surpass Visual Studio code snippets in terms of deployment convenience and value prediction. 3 types of templates — live templates, 'surround with' templates, and file templates — help deploy various constructs and create files while Template Explorer and Template Editor add a higher degree of extensibility and manageability. Development teams can share the templates that they create for a particular common solution. Last but not least, you can deploy familiar code snippets through ReSharper user interface.
Live templates are ReSharper's more intelligent version of Visual Studio's code snippets. ReSharper provides more than 20 live templates for C#, 17 live templates for VB.NET and 3 live templates for XML. The list includes templates for iterating through collections, writing assertion methods, creating new arrays, outputting values, coding LINQ queries and generating auto-properties, and more.
To apply a live template, press Ctrl+J to display the list of available live templates. If you know the abbreviation of a template that you want to deploy, just type it in the text editor, and press Tab in the completion list to expand the template:
After that, press Enter or Tab to navigate through template variables. Unlike code snippets, ReSharper can predict from the context which variables, fields, and types can be used in corresponding templates. In most cases you don't need to type anything yourself. Just choose from the list of suggested values.
'Surround with' Templates
'Surround with' templates are used to quickly enclose an expression, a single statement, or an arbitrary block of code with if/else, try/catch or other code constructs. ReSharper intelligently reformats the code, adjusts the selection, and/or repositions the caret as specified by the template.
To surround a piece of code with a template, select it and press Ctrl+Alt+J.
ReSharper lets you add new files to your project with predefined code fragments already generated in them. For example, you can create a new file with a class declaration, an interface, struct declaration, and so on. To choose from the list of file templates, click a node in Visual Studio's Solution Explorer, and press Alt+Ins.
Template Explorer and Template Editor
You can create your own templates and modify those that come bundled with ReSharper.
For editing templates, ReSharper provides Template Editor that opens in a separate Visual Studio code pane, allowing you to switch between your code and your template editing environment to make real-world testing of templates faster:
For managing templates, you can use Template Explorer that you can call by choosing ReSharper | Live Templates.
Once defined, any template can be easily shared among team members.
ReSharper recognizes NUnit tests and lets you run or debug them right in Visual Studio. You can run or debug:
- A single unit test
- All tests in a test class
- All tests in a project
- All tests in a solution
ReSharper provides two tool windows — Unit Test Explorer and Unit Test Sessions — to view, run and manage unit tests.
In addition, ReSharper adds special icons on the left gutter of the editor window. Click these icons to run or debug tests:
Unit Test Explorer
ReSharper presents Unit Test Explorer for reviewing the structure of tests in your whole solution. To open Unit Test Explorer, press Ctrl+Alt+U after building your solution. Using Unit Test Explorer, you can run any combination of tests in one or more unit test sessions.
Unit Test Sessions
ReSharper runs unit tests in the Unit Test Sessions tool window (Ctrl+Alt+T). It is designed to help you run any number of unit test sessions, independently of each other, as well as simultaneously. Sessions can be composed of any combination of tests. In the debugging mode, only one session can be run at a time.
The unit test tree shows the structure of tests belonging to a session, which you can filter to show only passed, failed or ignored unit tests. You can navigate to the code of any unit test by double-clicking it.
The progress bar and the status bar display the current progress. You can stop, run or re-build and re-run unit tests at any time.
The preview pane lets you analyze test results and navigate from a failed test's output to the code lines that originated the exception, all with a single click.
ReSharper 4 Full Edition ensures additional convenience for developers used to working with multilanguage solutions. Cross-language capabilities of ReSharper include the following:
- All navigation and search actions take code in all languages into account, including C#, VB.NET, ASP.NET, and XAML.
- Refactorings are designed to take into account all code in all languages. Whenever new source code must be generated in the process of refactoring cross-language code, refactorings work successfully. The only thing that cannot be done is recreating code written in one language in another language. In such cases a warning is displayed, letting you know about the conflict.
- Unlike Visual Studio's IntelliSense, ReSharper doesn't require projects in other languages to be compiled before symbols are available for Code Completion, Quick Documentation, and Parameter Info.
- By choosing ReSharper | Options | Languages | Common | Naming Style, you can define common naming conventions for all languages.
- Unit testing is available and equally useful for unit tests written in either C# or VB.NET.
- To-do items are collected from all languages (C#, VB.NET, XML, XAML, and ASP.NET).
Scenarios: How ReSharper Streamlines Common Coding Tasks
This section describes just a few use cases that show how ReSharper helps quickly perform routine developer tasks.
Create a New Class that Inherits an Interface
Problem. Create a new class that inherits an interface, and implement its members.
Suppose that you want to create a new class that inherits the IAbstractTreeControl interface. Here's how you can do it with ReSharper:
- Position the caret at the declaration of IAbstractTreeControl. (Keep in mind that pressing Ctrl+B at any usage of the interface helps you navigate to its declaration.)
- Press Alt+Enter. In the drop-down list that appears, select Create derived type:
- A new class that inherits IAbstractTreeControl will be created in the current file. If necessary, modify
the name of the new class:
- Keeping the caret at the declaration of the new class, press Alt+Enter. In the
drop-down list, select Move
to another file to match type name:
ReSharper will create a new file for the new class. (The same operation can be performed using the Move Type refactoring that you can launch by pressing Ctrl+R, O.)
- Position the caret at the declaration of the new class, and press Alt+Enter. In the
drop-down list, ReSharper will suggest to implement members of the inherited interface. Select Implement
- When the Generate dialog box shows up, select interface members to implement and configure additional
options. In order to be able to select individual options for every implemented member, click
- When you're done with setting generation options, click Finish. ReSharper will implement interface
members, throwing System.NotImplementedExceptions where necessary and selecting the body of the first
member for further modification:
Note that you can customize the default body of generated members to replace throw new System.NotImplementedException(); with other code. To do it, choose ReSharper | Live Templates, right-click Predefined Templates | No Language | System | defaultBodyTemplate and choose Edit to modify the default template.
- You can use ReSharper features to further modify the new class in the following ways:
- Pressing Alt+Ins anywhere within the class lets you generate constructors,
overriding members, delegating, formatting and equality members:
- Pressing Alt+Enter at the Root property lets you add another accessor to
the property or
implement it explicitly:
- Pressing Alt+Enter at the ExpandedChanged event helps you create event
custom implementation for the event, or implement it explicitly:
- Pressing Alt+Enter at any member's access modifier lets you change it:
- Pressing Alt+Ins anywhere within the class lets you generate constructors, additional properties, overriding members, delegating, formatting and equality members:
Search for Unused Members Solution-Wide
Problem. Find unused members in the scope of whole solution.
Solution. You can use Solution-Wide Analysis to search for inspections in the scope of whole solution. This feature can only search for errors, but the two inspections that you need to find unused members, namely Unused member in private type and Unused private member, are treated as warnings by default. To solve the problem, you need to make ReSharper highlight these inspections as errors:
- Choose ReSharper | Options to open the ReSharper Options dialog box.
- Choose Code Inspection | Inspection Severity to open the Inspection Severity tab.
- In the list of code redundancies, find two inspections: Unused member in private type and Unused private member.
- For each of these inspections, select Show as error in corresponding drop-down lists:
- Click OK to save changes and close the ReSharper Options dialog box.
Now, all you have to do is switch on Solution-Wide Analysis by double-clicking the gray circle indicator in the right corner of the status bar:
From now on, the Errors in Solution tool window will include links to unused code highlighted by the two inspections, in addition to compiler errors and ReSharper inspections that are treated as errors by default:
Of course, you can mark any other inspections listed in the ReSharper | Options | Code Inspection | Inspection Severity tab as errors, and they will be shown in the Errors in Solution in exactly the same manner.
Migrate to C# 3.0
Problem. Modify legacy C# code to take advantage of C# 3.0 features.
Solution. There are two complementary ways to solve this problem.
Using Quick-Fixes and Context Actions
- Suggestions and hints:
- Convert property to auto-property
- Convert property to auto-property with private setter
- Convert static method invocation to extension method call
- Convert to lambda expression
- Redundant explicit type in array creation
- Use object or collection initializer when possible
- Use 'var' keyword when initializer explicitly declares type
- Use 'var' keyword when possible
- Context actions:
- Convert anonymous method to lambda
- Initialize auto property from constructor parameter
- Inline method body as lambda
- Replace explicit type specification with 'var'
- Use collection initializer
- Use object initializer
Whenever you see a code construct that you'd like to upgrade to C# 3.0, position the caret on it, and if a red or yellow bulb appears to the left of the code line, press Alt+Enter — ReSharper will most likely suggest a context action or a quick-fix that will perform the required conversion automatically.
This technique is well suited to casual language upgrades that you can perform along with other coding tasks. Whenever you need to enforce migration to C# 3.0 constructors on a global basis, use the second technique.
Using Code CleanupCode Cleanup provides two settings that help introduce C# 3.0 constructs in batch mode in a scope as wide as the whole solution. To perform this task, do the following:
- Depending on the scope of migration, right-click a file, folder, project, or solution in Solution
Explorer, and select Cleanup Code in the context menu. The Code Cleanup dialog box will
- From the list of Code Cleanup settings, only two are required to perform the task: Use auto-property if possible and Use 'var' in declaration. To choose them, create a new profile by clicking Edit Profiles. The ReSharper Options dialog box opens at the Code Cleanup tab.
- Click Add to create a new profile.
- Specify a name for the new profile in the Profile name dialog box and click OK.
- In the Selected profile settings area, select Use auto-property if possible. Moving to the Use 'var' in declaration group of settings, select Can change type usage to 'var' in the Replace direction drop-down list. Choose appropriate settings in 'foreach' iterator declaration style and Local variable declaration style drop-down lists.
- Click OK to save the new profile. The Code Cleanup dialog box will be shown again.
- Select the new profile in the Available profiles area.
- Click Run to run the new profile. As a result, in the scope of your choice, properties with backing fields will be replaced with auto-properties (where possible), and 'var' keyword will be introduced according to selected settings.
We have tried our best to demonstrate how ReSharper helps save any developer's most valued asset — time, making many common tasks worth a click or a keystroke. The ability to make any C# project error-free without the need for continuous compilation, or navigation tools spanning the whole solution including C#, VB.NET, ASP.NET, XML, and XAML — isn't it impressive in its own right?
While it definitely is, there's always room for improvement, and we're currently working on our next release, ReSharper 4.5, which will bring support for VB9 (including the whole range of refactorings) in addition to major productivity improvements. Stay tuned for more good news for .NET pros!
Thank you for reading this guide and getting up to this point! We really hope you have discovered convenient ways to solve your development problems using ReSharper. If there's a feature that you had been looking for in ReSharper but didn't find it there, please submit your suggestions into our bug tracker — it's nothing other than user input that helps our product grow.
Should you have any questions regarding information contained in this guide, please contact:
- Ann Oreshnikova,
Phone: +7 (921) 930 6703
- Alexander Morozov,
.NET Products Marketing Manager
Additional ResourcesJetBrains ReSharper web site
ReSharper Documentation and Demos
JetBrains .NET Tools Blog
ReSharper 4 Default Keymap: Visual Studio scheme (PDF)
ReSharper 4 Default Keymap: ReSharper 2.x / IDEA scheme (PDF)
ReSharper 4 Feature Map
Appendix. ReSharper 4 vs Visual Studio 2008
|Feature||Visual Studio 2008||ReSharper 4|
|On-the-fly error highlighting||yes (SP1)||better|
|Solution-wide error highlighting||no||yes|
|Possible NullReferenceException analysis||no||yes|
|Quick-fixes to resolve errors||no||~200|
|Annotated .NET Framework classes||no||yes|
|Namespace import pop-up||yes||better|
|Smart completion (context-driven)||no||yes|
|Import symbol completion (completes types and extension methods from entire solution)||no||yes|
|Code snippets (templates)||yes||better|
|Generate file from template||yes||better|
|Generate type members||no||yes|
|Navigation & Search|
|Go to declaration||yes||yes|
|Go to base type||no||yes|
|Go to inheritor||no||yes|
|Go to reference||no||yes|
|Go to type||no||yes|
|Go to file||no||yes|
|Go to symbol||no||yes|
|View recent files||no||yes|
|View recent edits||no||yes|
|To-do browser (solution-wide)||no||yes|
|Stack trace explorer||no||yes|
|Optimize using directives||yes||yes|
|Remove code redundancies||no||yes|
|Organize type members||no||yes|
|Code cleanup: performs all cleanup tasks in one go||no||yes|
|Unit test explorer||no||yes|
|Multiple unit test sessions||no||yes|
- Available via Source Code Outliner power toy
- Available via MbUnit for ReSharper plugin
- Available via bundled plugin
- Available via Gallio plugin