12

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

gdoron
  • 147,333
  • 58
  • 291
  • 367

5 Answers5

12

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

leppie
  • 115,091
  • 17
  • 196
  • 297
  • 2
    I used it And then received the Color with Color.FromKnownColor(KnownColor color) http://msdn.microsoft.com/en-us/library/system.drawing.color.fromknowncolor.aspx – gdoron Nov 29 '11 at 11:48
6

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);
Alexander Galkin
  • 12,086
  • 12
  • 63
  • 115
  • That only works if you want your A is 00. A > 0 alpha will not compile. You'd need to convert it convert it to a decimal int, having a negative value. – Craig Celeste Jul 04 '12 at 19:36
4

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

Jon
  • 428,835
  • 81
  • 738
  • 806
  • They know this, they want to know how to get around it. – Ash Burlaczenko Nov 29 '11 at 11:30
  • 3
    @AshBurlaczenko: Isn't "you *cannot* get around this" a legitimate answer? – Jon Nov 29 '11 at 11:31
  • "you cannot get around this" is rare in coding, there is often a work-around, especially if the limitation is well-known. – Alexander Galkin Nov 29 '11 at 11:53
  • @AlexanderGalkin: Obviously. My point is that there is no head-on solution. If the constraints can be relaxed or redefined (e.g. you can modify the code for the attribute) the problem can be solved. – Jon Nov 29 '11 at 12:03
  • I Forgot the comment on this answer, look on my comment under the accepted answer. – gdoron May 09 '12 at 00:14
3
private static readonly Color MyLovedColor = Color.Blue;

I thanks that's the closest you can get?

Neil Thompson
  • 6,356
  • 2
  • 30
  • 53
0

What if you used the long value returned by the RGB function as your constant?

for example the value returned for a light blue RGB(51,255,255) is 16777011

so

Private Const ltBlue As Long = 16777011    
txtbox1.backcolor = ltBlue
Lakmi
  • 1,379
  • 3
  • 16
  • 27
lws
  • 1