I've set up some default colors in a C# winforms application like so:
readonly Color ERROR = Color.Red;
readonly Color WARNING = Color.Orange;
readonly Color OK = Color.Green;
As far as I am aware, readonly is essentially a constant for my purposes. If I attempt to define these as constants, the compiler indicates that it must be a compile-time constant, which Color is not.
Am I good leaving these as-is, or is there some way to define these constants that I should be aware of?
(The purpose is simply to have a single location in which to change all of the colors for logging purposes.)
Only literals can be defined as const
. The difference is, that const
values are hard-bakened into the assemblies that uses it. Should their definition change, then the call sites doesn't notice unless they get recompiled.
In contrast, readonly
declares a variable in a way that it cannot be reassigned after outside the constructor (or static constructor in case of a static readonly
variable).
So, you have no other way then to use readonly here, since Color is a struct, and no primitive data type or literal.
A const
field is a compile time
constant - you actually need code to run to determine the value of Color.Orange
though, internally probably defined as
public static readonly Color Orange = new Color(...);
Since this cannot be computed at compile time, your only option is readonly
which is set at runtime.
Also check out this article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With