In almost every project, I can't decide on how to deal with certain global constant values. In the older days, when I wrote C++ programs which didn't used dll's, it was easy. Just create and .h file with a number of const
that described certain constant values for my project. Then I had every file include it, and ta-da! It worked. Clean, respected the DRY principle and was simple.
Now my projects are C# .Net, which gives me a large range of options to deal with this problem. From what I know:
Create an Assembly whose only purpose is to hold constant values for my project. Every other Assembly should then reference this one. I respect DRY and KISS, since adding references is simple enough. Main problem here is that I'd need to recompile the whole source to update those values.
Use a app.config file and have all other Assemblies retrieve the constant during initialization. So I add the overhead of having to initialize everything just to access a global value. Is more flexible but also more painful.
Use resources. I think it's the same as with app.config.
So, I know there's a better way to do this constants declaration. But I don't know and, so far, have been unable to find how to do it. Can you please help? I have candy!
Thanks all
Er, assuming that your constants aren't enormous, you should just be able to declare them as public const
in a class of your choice:
namespace MyProject
{
public class Awesome
{
public const int SomewhatAwesome = 1;
public const int ExtraAwesome = 2;
/* etc */
}
}
You should include your const
members in the classes that they relate to, i.e. if SomewhatAwesome
and ExtraAwesome
are used for and by the Awesome
class, then they should be constants declared in that class. Don't create an extra assembly just to hold constant values, and don't create a dedicated static class or namespace for your constants unless there really is nothing else that groups the constants together.
The app.config
file is for settings that can be changed by the end user at runtime. Don't put constants that shouldn't change in that file. Resources are for "big" objects, such as text files and images, that would be tedious or impossible to include as literal class members. Don't put simple things like integers and short strings in resources.