Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare Color as constant

Tags:

c#

.net

How can I declare the Color type as const like this:

private const Color MyLovedColor = Color.Blue;

That doesn't work because the Color.Blue is static not const.

(readonly won't help me because I need the color for an attribute which "support" constants only

like image 630
gdoron is supporting Monica Avatar asked Nov 29 '11 11:11

gdoron is supporting Monica


2 Answers

Look at the KnownColor enumeration. It will likely cater for what you need.

like image 156
leppie Avatar answered Sep 27 '22 23:09

leppie


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

const string mycolor = "Blue";

Then, wherever you need your color, you perform the backward conversion:

Color mynewcolor = Color.FromName(mycolor);

I am sorry, but this is the only way to keep it const.

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

const int mycolor = 0x00FFFFFF;
Color mynewcolor = Color.FromArgb(mycolor);
like image 29
Alexander Galkin Avatar answered Sep 28 '22 00:09

Alexander Galkin