Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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){
 ....
}

like image 242
SigTerm Avatar asked Mar 05 '26 06:03

SigTerm


1 Answers

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.

like image 166
Jon Skeet Avatar answered Mar 06 '26 18:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!