Reputation: 26409
Consider this scenario.
struct
Color
(written by someone else)enum ColorCode
which implements html named color codes.ColorCode
to Color
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 int
s, 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
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 ColorCode
s to Color
s:
Color tmp = ColorCode.Aqua;
Upvotes: 2
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