Skip to main content

Move Declaration Near Reference

  • 2 minutes to read

Moves the declaration statement for a local variable near the first reference of that variable.

#Purpose

  • Moving variables declared near their first references improves code readability.
  • If a variable is used inside a nested code block (a loop, for instance) it is better to keep it declared within this code block so the code is easier to read and you can apply further refactorings such as Inline Temp, Replace Temp with Query and Move Initialization to Declaration.

#Availability

Available from the context menu or via shortcuts:

  • when the edit cursor, or caret is on a declaration of a local variable that is referrenced later in the method.

Note

This refactoring isn’t available if the local is first referrenced in a nested code block and then subsequently outside of it because the variable must be available outside the nested block for the subsequent reference.

#Example

int a = 15;
Method1();
Method2();
Method3();
b = a * 2;
return b;
Dim  a = 15
Method1()
Method2()
Method3()
b = a * 2
Return b

Result:

Method1();
Method2();
Method3();
int a = 15;
b = a * 2;
return b;
Method1()
Method2()
Method3()
Dim  a = 15
b = a * 2
Return b

#Animation

CSharpMoveDeclarationNearReference

See Also