I am comparing constants to static readonly class fields because they are used in the same way.
At a high level, constants are obviously dealt with at compile-time, while static readonly fields are set at the time they are evaluated at run-time. The fact that constant values are subsituted by the compiler means that any library/assembly which references the constant value will need to be recompiled if the constant value changes. Libraries referencing a static readonly field will reference the field and not the value, thus they will pick up any change in the field without the need for recompilation. So constants 0 - static readonly 1 in the area of maintainability.
Static readonly fields are able to hold reference types whereas constants will only support value types plus the special .NET ones string and null.
Finally, readonly fields can be set wherever and however the developer chooses meaning they can be lazy-loaded, and they can contain calculated values. A use for this that I found was when I was developing a system which could potentially use multiple databases. I needed the maximum permissible date from Oracle and Sql Server. Based on application configuration I was able to calculate this at runtime and still store the value in a static readonly field in the static Constants class along with regular constant values.
So, it appears that constants should be used when it is very unlikely that the value will ever change, or if no external apps/libs will be using the constant. Static readonly fields should be used when run-time calculation is required, or if it external consumers are a factor.
No comments:
Post a Comment