Firoso
Firoso

Reputation: 6685

How important is the usage of string resources? When is it appropriate/inappropriate to use/not use them?

My work has a policy (in a different department) that reads roughly as follows:

When applicable, store strings in String resources. If dynamic strings are needed use indexed place holders. Don't do this:

string myString = String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now);

But do this:

string myString = String.Format(Resource1.NameFormatString, myName, DateTime.Now);

What is the SO community's experience with string resources? When do you find it appropriate to use them? Is this a good policy in your opinion? Does it add to readability? effiency? Is it worth the encapsulation?

Upvotes: 2

Views: 245

Answers (4)

Nick Bedford
Nick Bedford

Reputation: 4435

Any human visible string (via UI) in a localised application needs to localised. The only case where one would not do this is with language independent strings, such as simple numbers or math formulas.

Upvotes: 0

James Conigliaro
James Conigliaro

Reputation: 3827

The definition of a good/bad policy depends entirely on if it meets its objectives. In the example given, the use of the resource string actually makes the code itself less readable - without looking up the string you won't know what placeholders are there or what order they appear in. BUT there may be a number of business reasonse why it is worth the little bit of extra effort. I'm not sure what your organizations reasoning might be, but here are a couple off the top of my head.

  • localization, you can swap out resource files and have your dates, numbers, etc. reformatted without touching the code

  • string reuse - if the same string appears in a number of different places you can define it once ... any changes would carry through to all instances of its use

  • translation - makes translating the application into other languages much much much easier.

Most policies are put in place for a well established reason, so the best thing to do is ask around. It can actually give you some great insight into the department's business.

Upvotes: 2

Robert S.
Robert S.

Reputation: 25294

In addition to greatly simplifying localization, moving your strings to a resource file means you can fix typos without redeploying your entire .NET application.

Upvotes: 2

Paul Sonier
Paul Sonier

Reputation: 39480

It's a critical requirement when dealing with internationalization (i18n); resources need to be localized to local languages, and that cannot be done when they are string literals in the code.

It's a good idea to code for this type of thing for any production code, as it can be quite the burden to go back and have to convert code to use resources if later i18n is required.

Upvotes: 9

Related Questions