How do you find yourself using Enum.Parse? Questions in order to promote a better solution...
Okay, so Enum.Parse throws an exception, as do many of the other Enum methods. A method like TryParse might be a bit cooler and would allow you to not throw an exception. The problem is, what in the heck do you really want from a TryParse method. I've been pondering this for a good portion of the day, I've written C# code, IL, CodeDOM code, and some Reflection.Emit crap. I've linked the methods to my NumberUtilities library to get the better string->int conversion and I've come up with the following list of questions.
-
Do you use Enum.Parse as a one off thing? In other words, do you casually parse a string value into an enum? If this is the case then I think you are probably happy with Enum.Parse, since you can't really care about the performance hit of an exception if you aren't doing a large number of parsings.
-
Would you use an instantiated parsing class that was custom built to parse a specific enum? In this case the first time you parse is slow, but successive parses are fast. This benefits you if you are parsing strings for the same enumeration many times and can somehow cache the parsing class. Should I build a static factory that holds onto these for you maybe?
-
Do you want out of range numeric values to return a failure? In some cases I'm thinking yes, but in others probably not. After getting an underlying type, I can easily range check for both the type and for values specified by the enumeration. No more specifying 20, when the enum only supports 0 through 5. Currently this isn't offered, so would you use it?
-
Do you want extended Flags support? In other words, should the same range checking apply for Flags values? Only defined flag bits can actually be set maybe?
The questions are tough. I just don't think enumerations are used enough to warrant a super fast, super efficient, strongly typed, and strongly range checked library. If I get enough response, I'll finish what I have up and put it out there as part of the NumberUtilities library. I would really like to hear opinions on some of these issues though, since I'm not familiar with how everyone else uses enumerations. In my case, I generally (if writing them out to file) store them in numeric form. So the name checking becomes rather unimportant. I don't generally care about the range checking, but have found need of it recently so I don't accidentally set things out of the allowable limits when fudging with configuration files.