How can I check if an int is a legit HttpStatusCode in .NET?

.net, c#, enumeration, http-status-codes

Solution

Instead of trying to parse the value simply us the IsDefined method

Enum.IsDefined(typeof(HttpStatusCode),value)

The reason why the case with "1" doesn't fail is that you can do binary arithmetic on enumerations. This is used a lot for flags, thus values not specifically in the enum might still be valid values

Problem

I wish to make sure that the number a person provides, is a legit HttpStatusCode. At first I thought of using `Enum.TryParse(..)` or `Enum.Parse(..)` but it's possible I get an invalid result with some bad data provided.. eg. ``` In: Enum.Parse(typeof (HttpStatusCode), "1") Out: 1 In: Enum.Parse(typeof (HttpStatusCode), "400") Out: BadRequest In: Enum.Parse(typeof (HttpStatusCode), "aaa") Out: System.ArgumentException: Requested value 'aaa' was not found. ``` Ok, so if I pass in a bad aaa value, I get the System.Argument exception. But when I pass in a number 1 (as text, not an int) i get the return value of 1. I would have expected this to fail and throw an exception. Passing a value of 400 does return the correct `BadRequest` enumeration. Any ideas, folks?

Original source