Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining colors as constants in C#

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

like image 539
JYelton Avatar asked Mar 21 '11 18:03

JYelton


2 Answers

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.

like image 52
codymanix Avatar answered Sep 22 '22 16:09

codymanix


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.

like image 35
BrokenGlass Avatar answered Sep 19 '22 16:09

BrokenGlass