Home > Refactorings > String.Format-specific refactorings shipped in Refactor! Pro

String.Format-specific refactorings shipped in Refactor! Pro

August 31st, 2011

Refactor! Pro provides several refactorings to create and organize the .NET String.Format call. The String.Format call is a static method that receives a string that specifies where the following arguments should be inserted, and how they should be formatted. You can specify the display options for each argument individually using the String.Format call.

These refactorings are:

  • Use String.Format
  • Introduce Format Item
  • Inline Format Item
  • Remove Redundant Call

The Use String.Format refactoring converts a composed string expression into a single String.Format call. This refactoring makes string concatenations much more readable and less error prone. It also makes it much easier to update your string, prepare its arguments for localization and add more parameters to it. However, on the other hand, the String.Format call may decrease performance a bit.

Imagine the following code:

Refactor! Use String.Format sample code

Before you apply the refactoring, you can see the resulting code (click the image to enlarge):

Refactor! Use String.Format preview

After we apply the Use String.Format refactoring, we will get the following code:

Refactor! Use String.Format result

This seems to be much more readable…

The Introduce Format Item refactoring adds a new format item to the string (e.g., “{0}”, “{1}”, etc.) which represents the selected text, and if necessary creates a new String.Format call to surround the string. The selected text is extracted to become an argument to the String.Format call and an argument placeholder is left in the format string. To apply the refactoring, select a part of a string that you would like to use as an argument to the String.Format call.┬áHere is the sample:

Refactor! Introduce Format Item preview

The Inline Format Item refactoring is the opposite of the Introduce Format Item. It inlines an existing String.Format argument into the text string, replacing the format item (e.g., “{0}”, “{1}”, etc.) , and creating a concatenated string, if necessary:

Refactor! Inline Format Item preview

This refactoring will remove the call to String.Format if it is applied in the last remaining argument:

A part of the Remove Redundant Call refactoring functionality allows you to remove the redundant String.Format call with a single string parameter:

Refactor! Remove Redundant Call preview

As always, the preview hint in every refactoring will show you the resulting code before you apply it. This allows you to see what code will be produced after the refactoring is performed.

Also, refer to other refactorings that work with strings.

Products: Refactor! Pro
Versions: 11.1 and up
VS IDEs: any
Updated: Dec/02/2011
ID: R036

Similar Posts:

  1. No comments yet. Be the first and leave a comment!