Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with C#'s enum?! It's so UGLY [closed]

Tags:

c#

enums

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?

like image 735
Sleeper Smith Avatar asked Jan 20 '23 19:01

Sleeper Smith


2 Answers

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

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

like image 121
Russ Clarke Avatar answered Feb 02 '23 11:02

Russ Clarke


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); }
}
like image 38
Andrey Avatar answered Feb 02 '23 11:02

Andrey