Visual Studio Tips and Tricks: How to rename identifiers using Refactor Rename

Introduction

In this post I will explain how to rename all the occurrences of an identifier using Visual Studio tool “Refactor Rename”

Description

In some situation we need to rename all the occurrences of an identifier like a variable name, a method name, a property, a class name etc. In that situation it is not easy to find and replace all the occurrences of that identifier. For example, you have written a method and declared a variable named “con” for MySQLConnection.

BeforeRename-RefactorRenameNow your boss comes and tells you to rename it to “mysqlcon” as he thinks it’s confusing. Here we can use Refactor Rename to rename it with no efforts. Follow these easy steps to do that

Step 1:

Right click on the identifier and click Refactor -> Rename to open Rename window. You can also use the shortcut (Ctrl+R, R) after selecting the identifier to open the Rename window.

Note: In VB.Net, we can directly open the Rename window by just clicking right on the identifier name and selecting the Rename option to open the Rename window. RefactorRename

Step 2:

In the Rename window, enter new identifier name in the “New name” field and click OK. Optionally you can select three options below the Location. When first option is enabled, it will show all the occurrences of the identifier being renamed. When second and third option is enabled, it will enable renaming of identifier in the comments and strings respectively.

Rename_2013-01-08_23-35-42

Step 3:

You can see preview of the identifiers being renamed in the Preview Changes dialog box as following. You can uncheck the identifier reference that you don’t want to rename. You can see location of each occurrences of the identifier in “Preview Code Changes” area by selecting an identifier in the top.

PreviewChanges-RefactorRename

Output:

Now, you can see in the following code that MySqlConnection identifier “con” has been renamed to “mysqlcon”. All the occurrences of “con” in the whole project has been renamed to “mysqlcon” by just a few clicks

PreviewChanges-RefactorRename3

Leave a Reply

Your email address will not be published. Required fields are marked *