6

When developing a project with VB6, we created a module and put every project-wide constant in it.

Now, using C#, how can we manage project-wide constants?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
odiseh
  • 25,407
  • 33
  • 108
  • 151

2 Answers2

13

Put them in a static class.

If you need this class referenced in many solutions create a project in which you put this class. Add references to it.

Victor Hurdugaci
  • 28,177
  • 5
  • 87
  • 103
0

You may also use a Singleton pattern. That is a class a class of which only one instance exists. The class itself is not static but you have only one instance of that class and you may provide it through a static property (MyConfig.Configuration in the sample).

public class MyConfig
{  
    static MyConfig configuration = new MyConfig();    

    public static MyConfig Configuration { return configuration; }

    readonly string version;
    public string Version { get { return version; } }

    MyConfig() { version = "0.1"; }
}
tomsseisums
  • 13,168
  • 19
  • 83
  • 145
smv
  • 585
  • 5
  • 12
  • 2
    A bit overkill, don't you think? – Camilo Martin Mar 28 '12 at 19:22
  • Absolutely, it can be a bit of overkill sometimes :-) Depending on project type, may also be "the right thing". – smv Apr 24 '12 at 20:47
  • When? I can't imagine how a big project would benefit from a singleton instead of a static class with enums. – Camilo Martin Apr 25 '12 at 03:46
  • 1
    "Configuration" can be a const in static class or a value in the appSettings; but something complex like the Windows Registry is configuration too. You may have structured (e.g master-details) configuration values stored in a db. If config values have complex structure, maybe they are best represented as instances of custom types. These instances (sometimes) end up as singletons. Other issues are "switching confuguration (whole or part) at runtime", "testing and/or validating"... I'm not advocating anything. In my opinion, the best thing is the simplest one _that solves the problem._ – smv Apr 25 '12 at 08:12
  • Ah, I see. I was thinking just about constants. I only store values that will never ever change in constants :) In regards to switching whole application configuration sets at runtime, I'd see it as code smell. Don't know because I never saw need to, but we both agree on that last sentence of yours. – Camilo Martin Apr 26 '12 at 15:10