.NET Tip of The Day
Learn one new .NET trick every day
Login or Join
.NET Tips & Tricks Community RSS

Those who prefer reading this site through RSS now can also subscribe for updates to .NET Tips & Tricks Community.

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
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.