Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible to declare a constant of type System.Drawing.Color? [duplicate]

Since I use "System.Drawing.Color.Gainsboro" in multiple places in my app:

if (tb.BackColor.Equals(System.Drawing.Color.Gainsboro)) {

...I wanted to make it a constant. But when I tried:

const System.Drawing.Color PSEUDO_HIGHLIGHT_COLOR = System.Drawing.Color.Gainsboro;

...I got, "The type 'System.Drawing.Color' cannot be declared const"

???

like image 302
B. Clay Shannon-B. Crow Raven Avatar asked Apr 26 '12 19:04

B. Clay Shannon-B. Crow Raven


1 Answers

The only types that can be const are those that have a literal representation in C#, as references to the constant are replaced at compile time with the literal value. There is no literal way to represent a color (you can only obtain a color either by a factory method or, as you are, using one of the static pre-existing colors).

You can, however, use a static readonly variable to achieve the same effect.

static readonly Color PSEUDO_HIGHLIGHT_COLOR = Color.Gainsboro;

For more info, see section 10.4 of the C# Language Specification

The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type.

For reference types, the only valid values are either a string literal or null.

like image 165
Adam Robinson Avatar answered Nov 15 '22 08:11

Adam Robinson