Visual Studio Refactoring Tips

ยท

2 min read

Visual Studio Refactoring Tips

5 Visual Studio Refactoring Tips ๐Ÿ’ก

Either for the sake of optimization or better code readability, we often refactor the code. Code refactoring includes many actions, such as deleting unnecessary code, encapsulating certain functionalities, changing the names of variables, and functions for better understanding, and so on.

If we use ๐•๐ข๐ฌ๐ฎ๐š๐ฅ ๐’๐ญ๐ฎ๐๐ข๐จ as an ๐ˆ๐ƒ๐„, it can help us a lot to quickly and successfully refactor the code.

Visual Studio makes things easy for us and has support for a lot of code changes. Today I am presenting 5 shortcuts in Visual Studio that I use all the time.

โ€ข ๐‘๐ž๐ง๐š๐ฆ๐ข๐ง๐  ๐ข๐๐ž๐ง๐ญ๐ข๐Ÿ๐ข๐ž๐ซ

When we want to change the name of a variable in a file/function, it often happens that the variable is used in several places.
Use ๐‚๐ญ๐ซ๐ฅ+๐‘, ๐‘ so that when you change the name of a variable in one place, all references are automatically changed.

โ€ข ๐„๐ฑ๐ญ๐ซ๐š๐œ๐ญ ๐Œ๐ž๐ญ๐ก๐จ๐

We often want to increase code readability by extracting a specific piece of code in one method into another method.
The hotkey ๐‚๐ญ๐ซ๐ฅ+. triggers the ๐๐ฎ๐ข๐œ๐ค ๐€๐œ๐ญ๐ข๐จ๐ง๐ฌ ๐š๐ง๐ ๐‘๐ž๐Ÿ๐š๐œ๐ญ๐จ๐ซ๐ข๐ง๐ ๐ฌ menu. From this menu, we can choose ๐„๐ฑ๐ญ๐ซ๐š๐œ๐ญ ๐Œ๐ž๐ญ๐ก๐จ๐ or ๐„๐ฑ๐ญ๐ซ๐š๐œ๐ญ ๐‹๐จ๐œ๐š๐ฅ ๐…๐ฎ๐ง๐œ๐ญ๐ข๐จ๐ง ๐„๐ฑ๐ญ๐ซ๐š๐œ๐ญ ๐‹๐จ๐œ๐š๐ฅ ๐…๐ฎ๐ง๐œ๐ญ๐ข๐จ๐ง.

โ€ข ๐‘๐ž๐ฆ๐จ๐ฏ๐ž ๐”๐ฌ๐ข๐ง๐ ๐ฌ

When we see a "grey" using statement at the beginning of the file, it means that the namespace is not used anywhere in the file - it is natural to delete it.
Using the ๐‘๐ž๐ฆ๐จ๐ฏ๐ž ๐”๐ง๐ง๐ž๐œ๐ž๐ฌ๐ฌ๐š๐ซ๐ฒ ๐”๐ฌ๐ข๐ง๐ ๐ฌ ๐จ๐ฉ๐ญ๐ข๐จ๐ง ๐Ÿ๐ซ๐จ๐ฆ ๐‚๐“๐‘๐‹ +. ๐ฆ๐ž๐ง๐ฎ, we delete all "using" statements that are not used.

โ€ข ๐„๐ฑ๐ญ๐ซ๐š๐œ๐ญ ๐ˆ๐ง๐ญ๐ž๐ซ๐Ÿ๐š๐œ๐ž

If we have a class, and we want to extract the Interface from that class (e.g., due to Dependency Injection), we can do that with the help of the shortcut ๐‚๐“๐‘๐‹ + ๐‘, ๐ˆ.
We can also select all the methods that interest us from the opened window.

โ€ข ๐…๐จ๐ซ๐ž๐š๐œ๐ก ๐ญ๐จ ๐‹๐ˆ๐๐

From CTRL+. the menu above the foreach loop, we will generally get a suggestion to ๐‚๐จ๐ง๐ฏ๐ž๐ซ๐ญ ๐ญ๐ก๐ž ๐œ๐จ๐๐ž ๐ญ๐จ ๐‹๐ˆ๐๐ to increase the readability of the code.
*Notice that typically loops are faster than LINQ queries because the compiler can optimize loops while LINQ queries extensively rely on method calls.

ย