C #: automatic conversion from enum to class

Consider this scenario.

  • There is struct

    Color

    (written by someone else)
  • There is enum ColorCode

    one that implements html named color codes.
  • There is a static function that converts ColorCode

    toColor

  • I want to be able to do this:

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

How can I do this without copying the text 140 times?

I don't care what ColorCode

(enum, class, whatever) if this line works.

Problem:

C # doesn't allow me to define operators for enums. I also don't have macros to make some nice human readable table in ColorCode

.

Limitation

Content ColorCode

must be available as int

s, but must be assigned / converted to Color

.


Code snippets:

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

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

      


+3


source to share


2 answers


You can write an extension method to enumerate:

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

      

Then you could:



Color tmp = ColorCode.Aqua.ToColor();

      

It's not really an implicit conversion, but it reads the way you probably get it.

+10


source


You can make a ColorCode

struct (better than a class because it really is a value) and then define an implicit listing from ColorCode

to Color

:

struct ColorCode
{
    int hex;
    public static readonly ColorCode
        AliceBlue = 0xF0F8FF,
        AntiqueWhite = 0xFAEBD7;
    // and the rest of the ColorCodes

    public static implicit operator Color(ColorCode cc)
    {
        return /* cc converted to a Color */;
    }
    public static implicit operator ColorCode(int cc)
    {
        return new ColorCode() { hex = cc };
    }
}

      



Implicit retraction from int

to Color

is just to simplify the definitions for your named color codes (so you can do, for example AliceBlue = 0xF0F8FF

). At this point, you can easily and implicitly convert ColorCode

to Color

s:

Color tmp = ColorCode.Aqua;

      

+2


source







All Articles