Skip to content

C# 6.0 - Bug in Enum.Parse #20576

@sujaysarma

Description

@sujaysarma

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions