Be careful with Enum.Parse

You may want to be more careful using Enum.Parse as you may end up with some unexpected behavior like I did. Casting int to an invalid enum value doesn’t throw exception. Have a look at this code snippet running with LINQPad:

enum PeopleType
void Main()
  ((PeopleType)Enum.Parse(typeof(PeopleType), "0")).Dump(); //Good
  ((PeopleType)Enum.Parse(typeof(PeopleType), "1")).Dump(); //Bad
  ((PeopleType)Enum.Parse(typeof(PeopleType), "2")).Dump(); //Ugly
  ((PeopleType)Enum.Parse(typeof(PeopleType), "3")).Dump(); //3 (no excptions)
  ((PeopleType)3).Dump();                                   //3 (no excptions)

Notice that the last two statements will not throw any exceptions although PeopleType doesn’t have the value of 3. Instead this will create an object of type PeopleType and the value of 3, sounds weird but true.
In case if you really want this to fail – or to do any validation check – you will have to use Enum.IsDefined method to check whether enum value or enum key actually exists.

Happy coding!

This entry was posted in Software and tagged . Bookmark the permalink.

1 Response to Be careful with Enum.Parse

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s