Table of content

Introduce Variable

Refactor with Introduce Variable to replace an expression with a temporary variable that explains the purpose of the replaced code.

Introduce Variable defines a temporary variable in the innermost scope of the selection, initializes the temporary variable with the replaced code, and replaces one or multiple occurrences of the expression with the temporary variable.


Introduce Variable is available for C/C++ and C# when your current selection is an expression or sub-expression. Select code to be replaced, and choose Introduce Variable from the Quick Action and Refactoring menu (Shift+Alt+Q) or the context menu (Right-Click or Shift+F10) of the text editor.

Variable Name and Type

If your expression occurs only once in the current scope, a dialog opens. Enter a meaningful name for your new variable.

Introduce Variable determines an appropriate type for your variable from the selected expression. Change the type if necessary.

The default name of your variable is sometimes derived from the selected expression.

In the following example, the default name, daysInMonth, was derived from the replaced method, GetDaysInMonth().

Multiple Occurrences

If your selected expression appears multiple times in the current scope, you will have the option of introducing a variable in lieu of the multiple occurrences. 

Only occurrences in the current scope that follow the selection can be replaced. If you want to introduce a variable for every occurrence of an expression in a block, make sure you select its first occurrence.


Introduce Variable places the definition of its temporary variable in the innermost scope of the expression, and replaces your selection in the original expression with the variable.

If the following example, IsValidMonth replaced "nMonth >= 1 && nMonth <=12".

When appropriate, Introduce Variable will remove residual parentheses from the resulting statement.

If the innermost scope is a single-line statement that follows a language construct such as if, else, or while,

Introduce Variable will insert braces to include the definition of the temporary variable in the scope of the expression.

You may move the definition of the temporary variable as appropriate, e.g. if you intend to use the temporary in a broader scope.


Use Introduce Variable to replace constants with meaningful variable names.

Capture a Return Value

Introduce Variable is also available in white space, in which case the refactoring will automatically select an expression and introduce a variable to capture the return value of a method/function call.

Location of Opening Brace

You can specify the location of open braces in the options dialog for Visual Assist.