Extract String to Resource
- 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
Place the caret on a string literal.
Note
The blinking cursor shows the caret’s position at which the Refactoring is available.
- Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
- Select Extract String to Resource from the menu.
- If the submenu expands, select the target RESX file or create a new one using the (Create new resource file) item.
- 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.
static void Main(string[] args) {
string helloWorld = Properties.Resources.HelloWorld;
Console.Write(helloWorld);
Console.ReadKey();
}
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.
using CRRDemo.Properties;
//...
static void Main(string[] args) {
Console.Write(Resources.HelloWorld);
Console.ReadKey();
}
Note
The Extract String to Resource (replace all) menu item extracts all string literals within the current method or accessor.