Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value is in Enum range without using IsDefined

Tags:

c#

enums

There are a few other Questions on how to convert Enums and what happens if the value parsed is out-of-range, like in:

public enum SomeTypes
{
    SomeType1 = 1,
    SomeType2 = 2,
    SomeType3 = 3
}

public class SomeClass
{
    ...
    var inRange = (SomeTypes) 1;
    var outOfRange = (SomeTypes) 5;
    ...
}

Going out-of-range will not produce any error. But I found the hard way that if you try to serialize-deserialize an enum with an out-of-range value you'll get weird errors. For example, I was getting something like

"error parsing the message or timeout exceeded"

which kept me looking for other reasons than the enum out-of-range.

Suggestions to handle this are by the means of the Enum.IsDefined. That seems to work quite nicely, but then there's this rather bold warning on msdn:

"Do not use System.Enum.IsDefined(System.Type,System.Object) for enumeration range checks as it is based on the runtime type of the enumeration, which can change from version to version."

So, my question is, can we safely use Enum.IsDefined or what is the correct way to check if the value of an enum is out-of-range without using the Enum.IsDefined?

like image 659
nando Avatar asked Sep 29 '22 09:09

nando


1 Answers

Use Enum.GetValues():

public bool IsInRange(int value){
  var values = Enum.GetValues(typeof(SomeTypes)).Cast<int>().OrderBy(x => x);

  return value >= values.First() && value <= values.Last();
}

[EDIT]

In case you want to check if the item is defined instead of just checking if it's inside the range, you can do similarly:

public bool IsDefined(int value){
  var values = Enum.GetValues(typeof(SomeTypes)).Cast<int>().OrderBy(x => x);

  return values.Contains(value);
}
like image 160
Joanvo Avatar answered Oct 04 '22 04:10

Joanvo