Richard
Richard

Reputation: 5998

Avoid exceptions when parsing enum value from string?

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.

Upvotes: 3

Views: 9582

Answers (4)

Michael Levy
Michael Levy

Reputation: 13297

As others have stated, the TryParse methods return a boolean on failure instead of throwing an exception. But also, look at http://msdn.microsoft.com/en-us/library/essfb559.aspx. It lists the Exceptions that may be thrown, so rather than catching the generic Exception, you could catch the specific exceptions being thrown like ArgumentException. The example on that page shows catching ArgumentException.

Upvotes: 3

Sean U
Sean U

Reputation: 6850

Use Enum.TryParse() instead. It returns a boolean value to indicate success or failure, and it's generic so it also saves you the juggling with casting.

bool success = Enum.TryParse(queryStringKeyValue, out this.myEnum);

Also, you shouldn't be able to assign null to an enumeration, assuming that field isn't actually of type MyEnum?.

Upvotes: 4

David Clarke
David Clarke

Reputation: 13266

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

MyEnum myEnum;
if (Enum.TryParse<MyEnum>(queryStringKeyValue, out myEnum))
{
    // successfully parsed enum
}

Upvotes: 4

Mark Hall
Mark Hall

Reputation: 54552

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.

Upvotes: 5

Related Questions