4

Seriously. C#'s enum's just a plain Eyesore. (IMO).

When you parse it from a string, you get a whole line of bloated legacy looking code:

(EnumType)Enum.Parse(typeof(EnumType), value);

Seriously? A parse method that takes in a type parameter, and spits out an object?! When really, it could be:

Enum.Parse<EnumType>(value);

It's a value type. So you can't use "as" instead of type cast. It's doesn't share a base type. So you can't write an extension for it either. You either resort to a static "Helper class" (woohoo.... ) or you resort to... bolting extension method on a string?! Worse than failure?.

Anyone got something elegant?

6
  • You may want to rephrase the wtf's
    – jb.
    May 10, 2011 at 1:59
  • EnumType.Parse(value) dont work?
    – ariel
    May 10, 2011 at 2:01
  • 1
    Is there a real question in here? You can make an extension method to convert any string into an enum with .ToEnum<EnumType>(). Just hides the ugliness. May 10, 2011 at 2:03
  • 1
    Language and tone are really inappropriate.
    – Andrey
    May 10, 2011 at 2:05
  • 3
    Despite the rantish tone this is actually a pretty good question...I say keep it. May 10, 2011 at 3:28

2 Answers 2

8

.Net 4 has added a lot of ... niceness ... to Enum:

http://reedcopsey.com/2009/10/26/long-overdue-enum-goodness-in-net-4/

6
1

I am coding for .net and never have a failure with enum. It is elegant for certain places, what you are trying to achieve is not elegant. Casting several enums to common base? What for? Enum is sort of strongly typed constant set and should be used like this. Parsing enum is not that frequent task that writing (EnumType)Enum.Parse(typeof(EnumType), value); becomes annoying. If it really does go on and write:

static class EnumHelper
{
   public T Parse<T>(string val) { return (T)Enum.Parse(typeof(T), val); }
}
3
  • He didn't actually say Failure, that was a transition from WTF and a tounge-in-cheek reference to dailywtf :) but I agree completely, if you're using Enums like this, you're possibly doing the wrong thing. May 10, 2011 at 2:22
  • "You either resort to a static "Helper class" (woohoo.... )". And no, I'm not trying to cast to common base. I want to do exactly what you are doing, but have "enum generic constraint" on the type T. You won't know you have passed in a wrong Type T until run time. May 10, 2011 at 2:45
  • @Sleeper Smith true. best you can is to add where T : struct
    – Andrey
    May 10, 2011 at 11:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.