I've been writing C# for seven years now, and I keep wondering, why do enums have to be of an integral type? Wouldn't it be nice to do something like:
enum ErrorMessage
{
NotFound: "Could not find",
BadRequest: "Malformed request"
}
Is this a language design choice, or are there fundamental incompatibilities on a compiler, CLR, or IL level?
Do other languages have enums with string or complex (i.e. object) types? What languages?
(I'm aware of workarounds; my question is, why are they needed?)
EDIT: "workarounds" = attributes or static classes with consts :)
The purpose of an Enum is to give more meaningful values to integers. You're looking for something else besides an Enum. Enums are compatible with older windows APIs and COM stuff, and a long history on other platforms besides.
Maybe you'd be satisfied with public const members of a struct or a class.
Or maybe you're trying to restrict some specialized types values to only certain string values? But how it's stored and how it's displayed can be two different things - why use more space than necessary to store a value?
And if you want to have something like that readable in some persisted format, just make a utility or Extension method to spit it out.
This response is a little messy because there are just so many reasons. Comparing two strings for validity is much more expensive than comparing two integers. Comparing literal strings to known enums for static type-checking would be kinda unreasonable. Localization would be ... weird. Compatibility with would be broken. Enums as flags would be meaningless/broken.
It's an Enum. That's what Enums do! They're integral!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With