How can I associate a value with an enum type?

  • Thread starter Thread starter steve bull
  • Start date Start date
S

steve bull

I am sure this is a really basic question but I don't see an easy way to do it.

I have an enum

public enum ColorType
{
red = 0,
green = 1,
blue = 2,
hue = 3,
saturation = 4,
brightness = 5
}

How can I associate a fixed value with each enum type? E.g. red is 255, hue=360 etc. Well, actually 255/fixedValue,
360/fixedValue etc.

I realize I could put these in a method with a switch statement and return the value but since the values are static or
at least only need to be calculated once at when the class is initialized it seems a waste of resources when I could end
up doing the calculation many times.

Is there a recomended way of doing something like this or at least a good way that doesn't involve lots of recasting of
the enum to ints.

Thanks,

Steve
 
I'm confused by our question. Should ColorType.Red hold a 0
or 255? It could hold either.

Recasting of enum to int is very fast...
 
I am using the enum within a widget to control the color. The enum determines which color type the widget controls.

If I used 255 etc then Red, Green and Blue would all have the same associated value - 255. I could not index off that
and know which color type I am dealing with. In fact there is no reason I couldn't have multiple values associated with
red.


Steve
 
you should use a composite way.
For example
enum firstEnum : byte
{
a=0x0,
b=0x1,
c=0x2
.....
}
enum secondEnum: short
{
a=0x100,
b=0x101,
c=0x102,
....
}

enum compositeEnum : int
{
aa = firstEnum.a | secondEnum.a
}

or something similar. I think there is no need to define a compositeEnum
just use bitwise operations in your code..
 
Althought I don't really understand why you do it that way, you can solve
your problem with an array provided your color enum is sequential.

public enum ColorType
{
red = 0,
green = 1,
blue = 2,
hue = 3,
saturation = 4,
brightness = 5
}

ColorType SelectedColor = ColorType.red
int [] ColorMap = {255, 360 ,111, 322, 584, 641} // any value required
int MapedRed = ColorMap[(int)SelectedColor] ;

/LM
 
thank you. it works fine for me.

steve



Althought I don't really understand why you do it that way, you can solve
your problem with an array provided your color enum is sequential.

public enum ColorType
{
red = 0,
green = 1,
blue = 2,
hue = 3,
saturation = 4,
brightness = 5
}

ColorType SelectedColor = ColorType.red
int [] ColorMap = {255, 360 ,111, 322, 584, 641} // any value required
int MapedRed = ColorMap[(int)SelectedColor] ;

/LM

steve bull said:
I am using the enum within a widget to control the color. The enum
determines which color type the widget controls.

If I used 255 etc then Red, Green and Blue would all have the same
associated value - 255. I could not index off that
and know which color type I am dealing with. In fact there is no reason I
couldn't have multiple values associated with
red.


Steve
 
Back
Top