NDepend

Improve your .NET code quality with NDepend

Top 10 Visual Studio Refactoring Tips

With the version 2019 Visual Studio is now mature when it comes to refactoring. This post proposes a tour of the top 10 most used refactoring actions in my opinion.

Short GIF is an excellent way to help get started with those Visual Studio tips. See others related posts based also on short GIFs here:

1) Renaming an Identifier

With Ctrl+R,R you can rename any code identifier: a variable, a field, a class… The renaming experience is pretty clean when only one source file is concerned since all references in file get updated live while typing the new name:

Renaming a variable in Visual Studio
Renaming a variable in Visual Studio

When renaming an identifier impacts several source files, like when renaming a class, several UI details improve the user experience:

  • In the top-right panel we see: Renaming X references in Y files
  • In the top-right panel we get the checkbox: Rename file, this is quite useful since often the file name and the class name are in-sync.
  • We get the possibility to preview all changes in all files in a Preview Change window.
Renaming a class in Visual Studio
Renaming a class in Visual Studio

2) Extract Method

The hotkey Ctrl+. triggers the Quick Actions and Refactorings menu. If you are not used yet to Ctrl+. I’d advise training especially this one because it is a powerful shortcut. You’ll see that most other refactoring presented here rely on the Ctrl+. hotkey.

If one or several instructions are actually selected in a method, the Extract method and Extract local function menus are proposed. A large tooltip is immediately shown to preview the changes. Then just click Enter and terminate the refactoring action by naming the NewMethod identifier.

Extract Method with Visual Studio
Extract Method with Visual Studio

3) Remove and Sort Usings

To make your code cleaner it is recommended to maintain for each source file the list of using ordered alphabetically with unnecessary usings removed. Both actions can be done automatically with Visual Studio top menu > Edit > Intellisense > Remove and Sort Usings. I wish a default shortcut was assigned to this common refactoring (of course you can still assign a shortcut to this action from Visual Studio top menu > Tools > Options > Keyboards.).

Remove and Sort Usings with Visual Studio
Remove and Sort Usings with Visual Studio

Actually it is possible to remove all unnecessary usings at once in a Visual Studio project or solution thanks to the bulb that appears in the code editor gutter when selecting an unnecessary using faded away.

Remove unnecessary usings with Visual Studio
Remove unnecessary usings with Visual Studio

4) Add Missing Usings when Pasting

When pasting some code it is quite irritating to get some errors because of some missing usings. Once the code has been pasted, you can click Ctrl+. to ask Visual Studio to add missing usings for you:

Add missing usings after pasting with Visual Studio
Add missing usings after pasting with Visual Studio

5) Generate Property from Constructor and Generate Constructor from Properties

Once again the magical Ctrl+. hotkey can be used when selecting a parameter into a constructor signature, to generate the corresponding property.

However I haven’t found a way to generate several properties in a row. I’d expect that selecting several parameters and then Ctrl+. would propose to generate several properties in a row but it is not the case, and there is no Create properties for all parameters menu.

Generate property from constructor with Visual Studio
Generate property from constructor with Visual Studio

The same way you can generate a constructor from the selected properties.

Generate constructor from selected properties with Visual Studio
Generate constructor from selected properties with Visual Studio

Both quick actions work with fields also.

6) foreach to LINQ

When the editor carret is over a foreach loop, the hotkey Ctrl+. proposes to convert the foreach loop to a LINQ query. This conversion is not always possible but it is smart enough. For example it can convert a if(condition){continue} within the loop into a where condition LINQ clause.

Notice that typically loops are faster than LINQ queries because the compiler can optimize loops while LINQ queries extensively rely on method calls. But in non-performance-critical code region LINQ queries is often a more readable, concise and maintainable way of writing code.

Converting a foreach loop into a LINQ query with Visual Studio
Converting a foreach loop into a LINQ query with Visual Studio

7) Extract Interface

When the editor carret is over a class name the hotkey Ctrl+. proposes a quick-actions list that includes: extract an interface from the class members. Ctrl+R,I can be used instead to directly show the Extract Interface dialog. The Extract Interface dialog proposes to define the interface name (per defaut set to “I{class name}”) and the member list to include in the interface.

Extracting an interface from a class with Visual Studio
Extracting an interface from a class with Visual Studio

8) Move Type to Namespace

When the editor carret is over a type name, the hotkey Ctrl+. proposes the quick-actions list that includes: move to namespace. The Move to namespace dialog is smart enough to propose intellisense and auto-completion based on existing namespaces. However the type’s source file is not moved automatically to the folder corresponding to the namespace chosen, this must be done manually in the Solution Explorer. I hope this move will be done automatically in the future.

Move class to namespace with Visual Studio
Move class to namespace with Visual Studio

9) Add Parameter to a Method

You can add a named parameter to a method call location. Then the hotkey Ctrl+. proposes the refactoring Add parameters to the method called. The method signature is then refactored with the extra parameter but other calls of the method are left untouched. It means that now these other calls provoke a syntax error and must be fixed with the extra parameter.

Add parameter to a method with Visual Studio
Add parameter to a method with Visual Studio

10) Convert to interpolated string and simplify interpolation

When the carret is over a call to string.Format() call the hotkey Ctrl+. proposes the refactoring Convert to interpolated string. String interpolation with the syntax $”{parameter}” has been introduced with C#6 in 2015. Then if possible some elements like call to PadLeft() are grayed in code. This is a sign that the string interpolation can be simplified once again with the hotkey  Ctrl+. over those grayed elements.

Convert to interpolated string with Visual Studio
Convert to interpolated string with Visual Studio

Conclusion

Over the years thanks to massive effort put in Roslyn, Visual Studio got better and better when it comes to refactoring actions proposed out-of-the-box. Many more refactoring than those 10 are proposed: read the list of refactoring and list of quick-actions.

When we talk about Visual Studio and refactoring the case of Resharper immediately comes in the discussion. For more than a decade Resharper has been the tool of choice to improve the productivity with many refactoring actions and more great features. My independent opinion in the VS vs. R# debate (in 2020) is that R# is still a bit more powerful despite VS being now quite mature. However it seems to me that the fact that VS is now quite mature with refactoring is not popular enough, hence I hope this post can help spread the word. And if you ask, yes I still code with R# in VS despite R# slowing down a bit the IDE, but I find myself using it less often. Within the next years we can expect both VS improvements in terms of refactoring and R# improvements especially in terms of performance.


Actually the word refactoring has really two meanings:

  • Short and quick productivity refactoring actions as presented here.
  • Large scale refactoring that are necessary when the architecture of a legacy doesn’t fit anymore the planned evolution and maintainability requirements.

Large scale refactoring must be discussed extensively. The number one prerequisite for a successful large scale refactoring is a solid understanding of the legacy code architecture. This is where the tool NDepend with its new dependency graph and dependency matrix can really help. Here are two short videos that explain how:

My dad being an early programmer in the 70's, I have been fortunate to switch from playing with Lego, to program my own micro-games, when I was still a kid. Since then I never stop programming.

I graduated in Mathematics and Software engineering. After a decade of C++ programming and consultancy, I got interested in the brand new .NET platform in 2002. I had the chance to write the best-seller book (in French) on .NET and C#, published by O'Reilly (> 15.000 copies) and also did manage some academic and professional courses on the platform and C#.

Over the years, I gained a passion for understanding structure and evolution of large complex real-world applications, and for talking with talented developers behind it. As a consequence, I got interested in static code analysis and started the project NDepend.

Today, with more than 8.000 client companies, including many of the Fortune 500 ones, NDepend offers deeper insight and understanding about their code bases to a wide range of professional users around the world.

I live with my wife and our twin babies Léna and Paul, in the beautiful island of Mauritius in the Indian Ocean.

Comments:

Comments are closed.