Does anyone have a more elegant solution to parsing enums? The following just seems like a mess to me.
UserType userType = (UserType)Enum.Parse(typeof(UserType), iUserType.ToString());
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I often make a generic helper for it:
You can combine that with Jon Skeet’s Unstrained Melody (or any other post IL processor) to get a proper type constraint on an enum, but that is optional.
Then you can use it like this:
The .NET Framework 4.0 also comes with
Enum.TryParsewhich also offers a similar syntax, and offers a way to handle if the parse fails. For example: