0

Say that I have this Enum:

enum GradeEnum
{
    A = 1,
    B = 2,
    C = 3,
}

Then I do

GradeEnum grade = (GradeEnum)Enum.Parse(typeof(GradeEnum),"234");

Then there no error triggered and the grade variable value is 234. But if I do comparaison with value of GradeEnum as expected the grade variable has not matched value.

Question, why is there no exception trigger by the Parse method?

Muffun
  • 726
  • 1
  • 9
  • 27

1 Answers1

5

You should use Enum.IsDefined to check whether enum is defined or not.

In order to parse and also validate you need both methods.

GradeEnum grade = (GradeEnum)Enum.Parse(typeof(GradeEnum), "234");
if (!Enum.IsDefined(typeof(GradeEnum), grade))
    ; // throw exception

Or use TryParse mentioned in comment bellow, forgot that!

string gradeValue = "234";
GradeEnum grade;
if (Enum.TryParse(gradeValue, out grade))
{
    // success
}
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • 1
    Ok, why not `Enum.TryParse`? – Tim Schmelter Aug 25 '17 at 14:26
  • 1
    This doesn't answer the question: _" why is there no exception trigger by the Parse method?"_ But it was already answered [here](https://stackoverflow.com/questions/6741649/enum-tryparse-returns-true-for-any-numeric-values) – Tim Schmelter Aug 25 '17 at 14:28