Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generated constants for enum values

Tags:

c#

enums

I'd need to store some properties of the enum's entries in their constants. For example indicate whether a color is cold or warm.

enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}

In C++ I would define a macro to generate bitmasks for the constants. Something like:

#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

  ...
  Gray   = ((2 << 8) | 0),
  ...

Any ideas?

P.S.
Yes, I'm a syntactic sugar freak. :D

like image 411
armen Avatar asked Sep 14 '26 08:09

armen


1 Answers

You should use attributes at the enum values. Read this article, it's pretty good:

http://www.codeproject.com/KB/cs/enumwithdescription.aspx

Hope it helps!

like image 91
Ignacio Soler Garcia Avatar answered Sep 16 '26 23:09

Ignacio Soler Garcia



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!