I have a project which utilizes many global constants. Eventually I am planning to extract some parts of the program and create assemblies of its own.
Is it worthy (or is it possible?) to create an assembly for global constants alone (viz, GlobalConstants.dll), so that I can use this assembly in future assemblies?
This method will help me do less coding, and I can keep the same name for the constants across the projects.
On how many projects do you expect the same constants to be useful? If there is genuinely a case for it, then fine; otherwise... don't.
Of course, if you have some equally likely to be reused utility library, then they might make sense in there, as long as appropriately scoped by namespace and type.
Personally, until I had an actual, concrete purpose in moving them, I'd leave them alone.
While it is certainly possible to do and maybe even a pretty good idea, you should be aware of the fact that the C# compiler treats constants as values and not as references.
With this I mean that the C# compiler will replace all instances of the constant in you code and replace the "variable" with the value.
This means that even if you update the assembly GlobalConstants.dll
and copy it to one of the applications you have, you will need to recompile that application. Not doing so, will cause the application to use the old constant values.
To overcome this problem, you can simply use public static readonly
instead of public const
as the readonly
modifier differs from the const
in that it is treated by the C# compiler as a reference in code rather than a value.
One reason to create a separate constants assembly would be to allow "less complex" updates such as error messages and localizations where you can update the assembly as a hotfix and reduce the risk of breaking anything else.
Generally where we find sharing constants useful is having a business entity layer assembly which contains global constants - as business entities are the only layer in our arch. which can be accessed by (most) layers.
Having a separate assembly causes overheads, and depending on which constants you have, you may have some which are directly dependent on functionality - eg. a key which may be used to find a value in a Hashtable.