C#: automatic conversion from enum to class

Consider this scenario.

  1. There is a struct Color (written by someone else)
  2. There is enum ColorCode which implements html named color codes.
  3. There's a static function that converts ColorCode to Color
  4. I want to be able to do this:

    Color tmp = ....;
    tmp = ColorCode.Aqua;
    

How do I do this without copy-pasting text 140 times?

I don't really care what ColorCode is (enum, class, whatever) as long as the above line works.

Problem:

C# does not allow me to define operators for enums. I also do not have any macros to make some nice human-readable table within ColorCode.

Restriction:

Contents of ColorCode should be available as ints, but should be assignable/ convertible to Color.


Code fragments:

public enum ColorCode{
    AliceBlue = 0xF0F8FF,
    AntiqueWhite = 0xFAEBD7,
    Aqua = 0x00FFFF,
    Aquamarine = 0x7FFFD4,
    Azure = 0xF0FFFF,  ///Repeat 140 times
    ...
}

public static Color colorFromCode(ColorCode code){
 ....
}

Jon Skeet
people
quotationmark

You could write an extension method on the enum:

public static Color ToColor(this ColorCode colorCode)
{
    ...
}

Then you could have:

Color tmp = ColorCode.Aqua.ToColor();

It's not quite an implicit conversion, but it's as readable as you're likely to get.

people

See more on this question at Stackoverflow