Dotnet logo

.NET Tools

Essential productivity kit for .NET and game developers

How-To's

Ctrl Alt V for Variable

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:
Before the refactoring
Dialog:
Introduce constant
After:
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.

Technorati tags: refactoring, ReSharper, .NET, Visual Studio
image description