Home » C# » Parsing integer to enumerator with value out of the enumerator range

Parsing integer to enumerator with value out of the enumerator range

If you want to convert a integer value into the enumerator that contain this value you can explicit cast the value.

    public enum MyEnumType {
        KeyA = 1,
        KeyB = 2
    }

    class Program {
        static void Main(string[] args) {
            int myIntegerValue = 1;
            MyEnumType enu = (MyEnumType)myIntegerValue;
            Console.Read();
        }
    }

This will work if the value, in our example 1, is in the MyEnumType. It will also work if we use an integer over 2.

Since the .Net Framework 4, we can use the Parse and TryParse on enumerator. The TryParse let you parse the name of the enumerator or the value. This mean, you can parse “KeyA” and it will retrieve the enum for the value 1 or you can parse 1 and it will retrieve the enum for the value 1.

In real application, if the data is from outside, is always better to use TryParse because this one will indicate if it can parse without throwing an exception. Here is an example with Parse with wrong value followed by one with TryParse.

As you can see the Parse work with integer that is out of range but not for the named enumerator parsing, just for the value conversion.

What about the TryParse? Samething! It will return TRUE even if the value is out of range.

This can be problematic if you doesn’t have the control over the value. For example, the value is passed from Ajax call from the client side to your server as an Integer. You want to convert this one into an enumerator to continue to proceed as usual on the server. The way to ensure that the value is legit is to use Enum.IsDefined.

So, every time you want to Parse an enumerator from the external (as an integer from an Ajax request) you should check if the value is defined correctly because only using the parsing tool won’t tell you if you are out of range.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.