Rider Help

Introduce Field refactoring

Ctrl+R, F

This refactoring allows you to create a new field based on a selected expression, initialize it with the expression or from the constructor, and replace occurrences of the expression in the current type with references to the newly introduced field.

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

Before refactoringAfter refactoring
class ErrorHandler { public static void LogError(Exception e) { File.WriteAllText(@"c:\Error.txt", "Something has failed" + e); } public static void PrintError(Exception e) { Console.WriteLine("{0} : {1}", "Something has failed", e); } }
class ErrorHandler { private const string ErrorMessage = "Something has failed"; public static void LogError(Exception e) { File.WriteAllText(@"c:\Error.txt", ErrorMessage + e); } public static void PrintError(Exception e) { Console.WriteLine("{0} : {1}", ErrorMessage, e); } }

To introduce a field

  1. Select an expression in the editor.
  2. Do one of the following:
    • Press Ctrl+R, F.
    • Press Ctrl+Shift+R and then choose Introduce Field
    • Choose Refactor | Introduce Field in the main menu.
  3. If more than one occurrence of the selected expression is found, Rider displays the drop-down menu where you can choose whether to apply the refactoring to all occurrences or only to the current one.
  4. The Introduce Field dialog opens. Specify the name for the new field and choose the access modifier. Optionally, specify whether to add static and readonly modifiers to the field.
  5. Choose how to initialize the field:
    • Current member: initializes the field in the current member (this option is only available if you chose to replace a single occurrence or if all occurrences are within the current member).
    • Field initializer: initializes the field in the declaration.
    • Constructor(s): initializes the field in the constructor or constructors of the containing class; if there are no constructors, a parameterless constructor is created to initialize the field.
    • Introduce constant: creates a constant field. This option is only available if the value of the selected expression corresponds to a built-in type.
  6. To apply the refactoring, click Next.
  7. If no conflicts are found, Rider performs the refactoring immediately. Otherwise, it prompts you to resolve conflicts.
Rider. Introduce Field refactoring
Last modified: 11 October 2017

See Also