Ctrl Alt V for Variable

Posted on by Mikhail Kropotov

Nowadays it’s an open secret that refactoring is indispensible for creating clear, well-structured code. This change is reflected in the fact that in 2005, we saw several refactorings introduced in Visual Studio, including Rename, Extract Method, Encapsulate Field, and a couple of others.
However, this was not the first time that powerful and flexible refactorings were made available to C# developers. ReSharper’s rich set of refactorings, which keeps growing steadily from one release to the next, adds great value to Visual Studio.
Here is one of the sweet refactorings you’ll want to have at your disposal in C# and ASP.NET: Introduce Variable.
Introduce Variable lets you quickly create a variable from any expression. All usages of the expression are instantly replaced with the newly declared variable. Here’s a basic example:

  1. Select an expression from which to make a new variable.
    Before the refactoring
  2. Press Ctrl + Alt + V to bring up the refactoring dialog, then provide the necessary details for the new variable. Select the “Replace all occurrences” option (occurrences are neatly highlighted in the editor as soon as this dialog opens) – if that’s what you want to do, of course.
    Introduce Variable dialog
  3. After you click Continue, the code looks like this:
    After the refactoring

Ok, so that’s how you can use the refactoring on an existing piece of code. Another way is to introduce a variable on the go. If you type an expression, and then it hits you that it should be declared as a variable (or a constant), just introduce it as one and keep typing.
Here’s a simplified example (if we forget for a second that we already have System.Math.PI available…)
Before the refactoring
Introduce constant
After the refactoring
With ReSharper you can introduce other things, too: Introduce Parameter and Introduce Field. More on that later.
P.S. Don’t mind the typo (that is, if you spotted one) – it will be fixed in the upcoming bugfix release.

Comments below can no longer be edited.

1 Response to Ctrl Alt V for Variable

  1. ISerializable - Roy Osherove's Blog says:

    June 11, 2006

    Resharper Vs. Refactor! and CodeRush – Let the games begin.

    It feels like the VS.NET Add-in wars are coming this way again, and I’m glad. Here’s what DevExpress…


Subscribe to .NET Tools updates