Back to Devexpress

Extract String to Resource

coderushforroslyn-117337-refactoring-assistance-extract-string-to-resource.md

latest2.3 KB
Original Source

Extract String to Resource

  • Aug 03, 2020
  • 2 minutes to read

Purpose

This Refactoring is used to create resource entities from string literals. The best programming practices require each string literal to be declared in a resources file. This approach makes software localization much easier.

Availability

Available when the caret is on a string literal.

Usage

  1. Place the caret on a string literal.

  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.

  3. Select Extract String to Resource from the menu.

  4. If the submenu expands, select the target RESX file or create a new one using the (Create new resource file) item.

  5. Enter the name for the new resource and press Enter.

After execution, the Refactoring creates a new entity in the selected resource file or creates a new resource file and adds the selected string to it. After that, it replaces the string literal with the resource link and creates a Text Field on the resource name.

csharp
static void Main(string[] args) {
    string helloWorld = Properties.Resources.HelloWorld;
    Console.Write(helloWorld);
    Console.ReadKey();
}
vb
Sub Main()
    Dim helloWorld As String = Resources1.HelloWorld
    Console.Write(helloWorld)
    Console.ReadKey()
End Sub

In the example above you can also use the Remove Type Qualifier refactoring (C# only) and then Inline Temp on a helloWorld variable to make your code shorter.

csharp
using CRRDemo.Properties;
//...

static void Main(string[] args) {
    Console.Write(Resources.HelloWorld);
    Console.ReadKey();
}
vb
Sub Main()
    Console.Write(Resources1.HelloWorld)
    Console.ReadKey()
End Sub

Note

The Extract String to Resource (replace all) menu item extracts all string literals within the current method or accessor.

See Also

Move Type to File