So close...yet so far...
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...
Comments
- Anonymous
October 19, 2005
I've hit the same barrier in the past, and ended up with the same solution. It'd be nice if you could, I agree :)
http://codebetter.com/blogs/geoff.appleby/archive/2004/11/18/32533.aspx - Anonymous
October 19, 2005
The comment has been removed - Anonymous
October 20, 2005
Make it an attribute
http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=05046272-c28c-44e2-8ca1-9a50fe69599f - Anonymous
February 22, 2009
I saw two posts on Enums today on Eric Lipperts and Chris Rathjen's blog. Enums are significantly different