Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid exceptions when parsing enum value from string?

Tags:

c#

.net

In this example:

try
{
    this.myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), queryStringKeyValue);
}
catch (Exception)
{
    this.myEnum = null;
}

How to avoid the introduced dependency on catching a generic exception? I'm getting no clues from ReSharper. Ideally, I'd like to get rid of the try / catch.

like image 835
Richard Avatar asked Mar 17 '26 16:03

Richard


2 Answers

Try looking at Enum.TryParse

TryParse(Of TEnum)(String, TEnum) is identical to the Parse(Type, String) method, except that instead of throwing an exception, it returns false if the conversion fails. It eliminates the need for exception handling when parsing the string representation of an enumeration value.

like image 90
Mark Hall Avatar answered Mar 20 '26 08:03

Mark Hall


You can eliminate the exception by using Enum.TryParse(), e.g.

MyEnum myEnum;
if (Enum.TryParse<MyEnum>(queryStringKeyValue, out myEnum))
{
    // successfully parsed enum
}
like image 35
David Clarke Avatar answered Mar 20 '26 06:03

David Clarke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!