SigTerm
SigTerm

Reputation: 26409

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

Upvotes: 3

Views: 191

Answers (2)

Jashaszun
Jashaszun

Reputation: 9270

You can make ColorCode a struct (better than a class, because it really is just a value), and then define an implicit cast 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 };
    }
}

The implicit cast from int to Color is just to make the definitions for your named color codes easier (so that you can do, for example, AliceBlue = 0xF0F8FF). At this point, you can easily and implicitly convert ColorCodes to Colors:

Color tmp = ColorCode.Aqua;

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500495

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.

Upvotes: 10

Related Questions