Archive for April 23rd, 2008|Daily archive page
When to use constants, settings.settings and Resources.resx
When developing in Visual Studio (2005 upwards I think), you have several options when it comes to referencing strings in your code (and other types, but I’ll restrict to strings for the sake of conciseness). I think it is safe to say that usually you do not want to hard-code the string directly in the code, but should you create a constant ‘at the top’ of the class? or should you create a class for constants to use throughout the project/solution? or should you use the project settings (settings.settings)? or should you reference it as a resource? Whew, that’s a lot of options!
As I see it my guidelines would be:
- If the string will never need to be changed and is only relevant to the class in question just reference it as a constant within the class. This will keep it proximal to the code using it, whilst concentrating all the class constants in one place.
- If the string will never need to be changed and is relevant to multiple classes define it in a single class at a scope that makes sense (project/solution wide)
- If the string needs to be changeable by the end user at configuration time then settings.settings should be used.
- If the string needs to be changed based on the locale the application is running in (e.g. It contains text displayed to the user) then it should be put in the resources.resx file.
- If the string sensibly fits within a grouping of configurable items that could be applied to the application (e.g. you want to be able to ’skin’ your application so that multiple configurations can be chosen) then it should be put in a resources.resx file.
I think the question of settings vs Resources can be a little tricky, as far as I am aware the differences are:
- Resources.resx file are only modifiable pre-build, the end-user will not be able to change the contents; Settings.settings files are rolled up into the application’s configuration and are therefore customizable by the end user.
- Settings.settings files are not localization aware, they should not be used to make your app localizable. Resources should be used for this.
Comments (1)