ReSharper 2021.1 Help

Introduce Variable refactoring

ReSharper | Refactor | Introduce Variable…
Control+Alt+V
ReSharper_IntroVariable

This refactoring allows you to create a new local variable or constant based on a selected expression, initialize it with the expression, and finally replace all occurrences of the expression in the method with references to the newly introduced variable.

In the example below, we use this refactoring to replace two occurrences of the same string with a variable:

static void LogError(Exception ex) { Console.WriteLine("Something has failed..."); File.WriteAllText(@"c:\Error.txt", "Something has failed..." + ex); }
static void LogError(Exception ex) { var message = "Something has failed..."; Console.WriteLine(message); File.WriteAllText(@"c:\Error.txt", message + ex); }

Replace one or more occurrences of an expression with a variable

  1. Select an expression in the editor.

  2. Do one of the following:

    • Press Control+Alt+V.

    • Press Control+Shift+R and then choose Introduce Variable

    • Right-click and choose Refactor | Introduce Variable in the context menu.

    • Choose ReSharper | Refactor | Introduce Variable… in the main menu.

  3. If more than one occurrence of the selected expression is found, ReSharper displays the drop-down menu where you can choose whether to apply the refactoring to all occurrences or only to the current one.

  4. ReSharper adds the new local variable and suggests choosing its type and name. You can choose one of the suggestions or type your own values. Press Tab or Enter to move to the next input position. Shift+Tab to return to the previous input position.

This feature is supported in the following languages and technologies:

Language: C#Language: VB.NETLanguage: C++Language: HTMLLanguage: ASP.NETLanguage: RazorLanguage: JavaScriptLanguage: TypeScriptLanguage: CSSLanguage: XMLLanguage: XAMLLanguage: ResxLanguage: Build ScriptsLanguage: ProtobufLanguage: JSON
Feature is available in C#Feature is available in Visual Basic .NET Introduce variable in C++ Feature is not available in HTML Feature is not available in ASP.NET Feature is not available in RazorFeature is available in JavaScriptFeature is available in TypeScript Feature is not available in CSS Feature is not available in XML Feature is not available in XAML Feature is not available in Resource files Feature is not available in build script files Feature is not available in Protobuf Feature is not available in JSON

The instructions and examples given here address the use of the feature in C#. For details specific to other languages, see corresponding topics in the ReSharper by Language section.

Last modified: 08 March 2021