How-To's

ReSharper in Detail: Reformatting Code

ReSharper can reformat an arbitrarily selected block of C# or VB.NET code, all code in the current file, all files in a directory, the current project, or even the current solution, according to options configurable in:
 

  • ReSharper | Options | Languages | C# | Formatting Style for C# code, or
  • ReSharper | Options | Languages | Visual Basic .NET | Formatting Style for VB.NET code.

 
Once the formatting settings are configured, you can share them with your fellow team members to ensure uniform code appearance.
 
Whenever you have a file opened in the editor, select a fragment that you want to reformat, or, alternatively, don’t select anything, in which case reformatting will apply to the entire file. Then launch Reformat Code in one of three ways:
 

  • Choose ReSharper | Code | Reformat Code on the main menu.
  • Press Ctrl + Alt + F (no default shortcut in VS scheme).
  • Choose Reformat Code in the context menu.

 

 
The Reformat Code dialog box (shown above) contains several formatting options:
 

  • Optimize ‘using’ directives removes redundant namespace import directives from the source code. Note that this option is disabled when you have a selection – even if it includes the imports section of your file.
  • Shorten references replaces fully qualified names with short names where possible by importing namespaces.
  • Remove redundant ‘this.’ qualifier deletes unnecessary this keywords (note that it doesn’t do the same for VB.NET keyword Me).
  • Reorder type members (for C# code only) reorders type members according to patterns specified in ReSharper Options | Languages | C# | Type Members Layout.

 
After you have reformatted your code, ReSharper saves the state of check-boxes for future use. Subsequently, you can even launch Reformat Code silently, without opening the dialog box, by pressing Ctrl + Shift + Alt + F (or Ctrl+E, F in the Visual Studio keyboard layout).
 
An additional advantage is that you can execute reformatting via Solution Explorer. For example, you can reformat a specific C# code file, or all such files in a project or entire solution. Just right-click the required node and choose Reformat Code….
 
Additional links:
 
Kyle Baley explains how to remove regions with the Reformat Code feature (C# only)
An example of how you can customize a type member layout pattern
Tips for using Reformat Code with aspx pages
Joe White’s detailed review of ReSharper’s reformatting tools

Technorati tags: , , , , ,

Discover more