There’s a LOT to like in the 2.0 version of the Framework and Base Class Library.
But, I ran into something today that I feel is missing. Or at least, it’d be really cool of it was there.
I want to be able to override the ToString method on an enum.
I know, I know – on the surface, it sounds evil. Enums aren’t reference types, you nit! They’re value types (sort of). But, ever since enum got a ToString() method, I’ve been running into times I wanted to specialize the way it worked.
Today, the issue was that we want to future-proof some testcases. So, instead of using some strings directly, we want to enumerate their logical values, and use something to handle the logic of taking the logical value and intelligently produce the correct string (in this case, it was to deal with localization, but there’s more to it than that).
The simplest thing that came to mind would be to override the enum’s toString value. What we’re doing instead is a “ConvertEnumToString(enum value)”. It’s sort of a hack, because an uninformed consumer of the enum won’t know that he should use that method instead of calling enum.value.ToString() directly.
Anyone out there have suggestions on a better alternative? I toyed briefly with a static class with properties where we had enumerated values, but that’s not viable – can’t pass static types as parameters (we have code that wants an array of the enum, for example). A nonstatic class solves that problem but in cases where we just want to switch on the value, now we would have to pass around an instance where we could just look at the value before.
What am I missing?
Shine on, you crazy diamond…