- 3 minutes to read
Creates a new local variable initialized with the selected expression. Optionally replaces all occurrences of the expression inside this code block with a reference to the newly declared local variable.
This refactoring is known as Introduce Explaining Variable in Martin Fowler’s Refactoring book.
Introduce Local is great when you have a complicated expression or calculation that has been repeated multiple time in a code block, and you want to consolidate these multiple calculations into a single call. This will help reduce the complexity of code management because future changes to the code will be isolated to one place. Introduce local is also useful when you want to replace the calculation with a local variable that has a name that better explains what the calculation does - improving the readability and maintainability of your code.
- when an expression is selected.
Using the Intelligent Paste feature:
- when an expression is cut and subsequently pasted on an empty line inside the method or property, above the cut point.
- Right after Introduce Local has finished, Rename is called so that you have an opportunity to provide an appropriate name for the newly created local variable.
- If you extract the right-hand side of an assignment, Introduce Local automatically suggests a property name based on the assignment’s left-hand side.
- Introduce Local places the initialization of the local variable on the line immediately above the first reference to the variable.
- If you need a particular expression or calculation to be reused in several methods or properties, use Extract Method or Extract Property instead of Introduce Local.
- If you have already completed an Introduce Local refactoring and later need to reuse the calculation in several methods or properties, use the Replace Temp with Query refactoring in the assignment statement for the local variable. This will automatically invoke Extract Method for the assigned expression and Inline Temp for the variable.
- Introduce Local is the opposite of the Inline Temp refactoring.
- You can change the default name for the introduced local variable.
- You can disable automatic variable name suggestions.
- The extracted expression can be automatically embedded into parentheses.
c = (a + b) * 10;
c = (a + b) * 10
int d = a + b; c = d * 10;
Dim d As Integer = a + b c = d * 10