-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
As per this document: https://msdn.microsoft.com/en-us/library/essfb559(v=vs.110).aspx, the Enum.Parse() function is supposed to throw either an ArgumentException or an OverflowException if I try to parse in a value that is not a part of the Enum. The example in that same document however uses the Enum.IsDefined() function to make the determination instead of catching that exception. The reason is simple – the Enum.Parse() no longer throws those exceptions!
Simple script I ran in the C# Interactive in the VS 2017 IDE:
enum fooEnum {
. one = 1,
. two = 2,
. three = 3
. }
(fooEnum)Enum.Parse(typeof(fooEnum), "4")
4
fooEnum test = (fooEnum)Enum.Parse(typeof(fooEnum), "4");
test
4
fooEnum test = (fooEnum)Enum.Parse(typeof(fooEnum), "4");
Enum.GetName(typeof(fooEnum), test)
null
As you can see, I got no exceptions at all trying to parse in a value of “4” for my fooEnum enum. I recall in earlier versions the exception used to be thrown. This broke an application for me because I was betting on the exception to be thrown which it no longer does.