Resources vs. Hard-Coded Strings

Problem
You have a number of user-interface strings, but you don’t want to store them in code. What can you do?

Solution
Place all user-interface strings in a Resources (.resx) file. Storing them in a centralized location makes them easier to modify, spell check, and localize.

Example
Let’s say you’ve added a resources file to your project with the name UiStrings.resx. Here’s how you can reference a string resource named Message from the application code whose default namespace is TestAutomation.

string resourcesFile = "TestAutomation.UiStrings";
ResourceManager resources = new ResourceManager(resourcesFile, Assembly.GetExecutingAssembly());
string message = resources.GetString("Message");

Pro-tip
Store the ResourceManager reference in a variable that can be accessed by the entire application. This way, you won’t need to re-create it every time you need to retrieve a resource.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s