.NET Tip of The Day
Learn one new .NET trick every day
Быстрое пополнение счета телефона      Login or Join

Validate integer value before casting it to an Enum type

There is one thing you should watch out for when using enumerations. You can cast any integer to an Enum type and you will not get an exception message. Therefore if the value comes from an external source (for example, from user input) check it against an enum before casting. The easiest way to do it is to use Enum.IsDefined method:

    int submitedValue = 123;

    if (Enum.IsDefined(typeof(MyEnum), submitedValue))

    {

        //do casting here

    }



Note: because Enum.IsDefined loads reflection it should be used with caution because of its performance penalty.


via M. Parreira

9/27/2007

Comments:

Your article looks good. Can you explain me some real time example of using this situation?

Madhan 11/26/2007 12:16:14 PM

For example, when you reading data from external database/file and converting it into variable of enum type, don't rely on exception being thrown to catch invalid data.

kostya.ly 11/27/2007 1:30:10 PM

Name
URL
E-mail
Provide your e-mail address to receive notification about new comments.
Message
HTML tags are not supported.
Please add 7 and 6 and type the answer here:
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.