Defining colors as constants in C#

JYelton picture JYelton · Mar 21, 2011 · Viewed 16.5k times · Source

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.)

Answer

codymanix picture codymanix · Mar 21, 2011

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.