Reputation: 121
I have some constants that i would like to have at application level, like stored procedure names, user messages, and others. there is very less chance that i will ever change these resources.
Please let me know what is good practice for keeping constants in our application.
Is Resource dictionary is preferable over .cs file.
Regards AA
Upvotes: 3
Views: 595
Reputation: 9237
For starters, you're on the right track thinking about this stuff at all. Magic strings and other magic values are bad for lots of reasons.
Here are some guidelines we use:
We generally have three files per assembly, as needed: First, a constants file. This is usually as simple as Constants.cs. Put your constants (AND readonly statics that are not compile-time constant and never change) in this file. You could also include things that are configurable but MUST have a default value.
internal class Constants
{
public const LogLevel DEFAULT_LOG_LEVEL = LogLevel.Error;
public static readonly string APP_NAME = Configuration.ApplicationName ?? "Test Application";
}
Second, a file that reads configuration values and returns them as static values. This is generally Configuration.cs and is responsible for return ALL configuration values. This saves you from having to recompile to change a connection string, deal with a setting, or something else. The actual values reside in places like an .ini file, web.config or app.config, database table, or other location outside the source code. If the following example you could smatter ConfigurationManager.AppSettings["ApplicationName"] all over your code, but then what if you want to change the key of that appsetting? You have to find an rename all the reference to it. Just take the extra 30 seconds to do something like this, and all Configuration.ApplicationName.
internal class Configuration
{
public static string ApplicationName
{
get
{
return ConfigurationManager.AppSettings["ApplicationName"];
}
}
}
Finally, one or more resource files. This is where we put things like icons, images, unusual fonts, localized (or just changable) strings for display purposes, etc...
There is no specific right way do do this stuff, but I think the above will give you a place to start.
Upvotes: 3