6

This is a question regarding best coding practices. I would like to know the consensus about how to best avoid hardcoding strings and values in a .NET application. What I've seen so far where I have previously worked:

  • using resource .resx files
  • storing these values and strings in App.config or web.config
  • making a static class ApplicationStrings and declaring all the strings and values in there:

    public static class ApplicationStrings
    {
        #region constants
        public const string APPLICATION_NAME = "X";
        public const string APPLICATION_RESOURCEMANAGER_NAME = "ResourceManagerX";
        public const string APPLICATION_DEFAULT_LOGFILENAME = "log.txt";
    }
    

However, is not the 3rd method, just another hardcode? Does it make sense to have such a class? The benefit would be that all strings are in one place, but is that really avoiding a hardcode?

Also, if you have developed other habits for this situation, feel free to post.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Amc_rtty
  • 3,662
  • 11
  • 48
  • 73
  • 1
    I'd prefer static readonly fields over constants here. Constants are more for things that will have the same value forever. Which makes their binary versioning semantics a bit annoying. – CodesInChaos Jul 16 '11 at 22:47

4 Answers4

5

The main benefit is indeed to have all strings in one place and you only need to change it there to update the whole program. If different parts of your program use the same string and one instance gets updated, but another not, then you have a problem. This holds true for all literals, by the way.

And then with resource files there is the benefit of i18n and l10n. If you need it, but many large applications should.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • 1
    The advantage of resource files is that they can be replaced with other versions where necessary. You _can_ do that with source code files, of course, but somehow it's clearer that it's different data (i18n and l10n), not different functionality. – MRAB Jul 16 '11 at 22:45
1

in general i believe it is good practice to store all configurable data in a central config file so all the data is in one place and can be shared by other apps

plague
  • 1,908
  • 11
  • 11
1

In my opinion ApplicationSettings is only useful if your settings are (i) genuinely constants and (ii) of course truly public. If either of these cases is not true then this is not ideal and your choice is back to a .config file .resx

Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
0

Well, I think that ApplicationStrings is a good solution

Mark Segal
  • 5,427
  • 4
  • 31
  • 69