I have various constants that my program uses. Some are string
s, some are int
s, and some are double
s. What's the best way to store them? I don't think I want an Enum, because the data is not all the same type, and I want to manually set each value. Should I just store them all in an empty class, or is there a better way?
views:
862answers:
8IMO using a class full of constants is fine for constants. If they will change semi-occasionally I recommend using AppSettings in your config and the ConfigurationManager class instead.
You probably could have them in a static class, with static read-only properties.
public static class Constants
{
public static string SomeConstant { get { return "Some value"; } }
}
First, if your constants are to be used from multiple assemblies use static readonly
variables. If they are used only in your assembly go ahead with const
.
What I like to do is the following:
internal static class ColumnKeys
{
internal const string Date = "Date";
internal const string Value = "Value";
...
}
An empty static class is appropriate. Consider using several classes, so that you end up with good groups of related constants, and not one giant Globals.cs file.
Additionally, for some int constants, consider the notation:
[Flags]
enum Foo
{
}
As this allows for treating the values like flags.
Yes, a static class
for storing constants would be just fine, except for constants that are related to specific types.
Another vote for using web.config or app.config. The config files are a good place for constants like connection strings, etc. I prefer not to have to look at the source to view or modify these types of things. A static class which reads these constants from a .config file might be a good compromise, as it will let your application access these resources as though they were defined in code, but still give you the flexibility of having them in an easily viewable/editable space.
This is the best way IMO. No need for properties, or readonly:
public static class Constants
{
public const string SomeConstant = "Some value";
}
If these Constants are service references or switches that effect the application behavior I would set them up as Application user settings. That way if they need to be changed you do not have to recompile and you can still reference them through the static properties class.
Properties.Settings.Default.ServiceRef