Declare color as permanent

How can I declare a Color type as const as follows:

 private const Color MyLovedColor = Color.Blue; 

This does not work because Color.Blue is static, not const.

(readonly will not help me because I need a color for an attribute that only supports constants

+7
source share
4 answers

Take a look at the KnownColor listing. This will most likely help you with what you need.

+8
source

You can only assign const to a value that is a literal. In your case, I would prefer a string literal and define your color as follows:

 const string mycolor = "Blue"; 

Then, wherever you need your color, you do the inverse transform:

 Color mynewcolor = Color.FromName(mycolor); 

Sorry, but this is the only way to keep it const .

EDIT . Alternatively, you can also save your color as (A) RGB attributes stored in a single int value. Note that you can use the hexadecimal literal to explicitly set the different components of your color (in the ARGB sequence):

 const int mycolor = 0x00FFFFFF; Color mynewcolor = Color.FromArgb(mycolor); 
+5
source

System.Drawing.Color is a struct , which means you cannot have its constant value.

+4
source
 private static readonly Color MyLovedColor = Color.Blue; 

I thank you the closest you can get?

+3
source

All Articles