I found an edge case for enum values and want to know whether there is a solution for that problem in .net5
I´ve got the following enum:
public enum SomeEnum : ushort
{
FirstValue = 0x9D80,
SecondValue = 0x9DCE,
ThirdValue = 0xEBA0,
Unknown = 0xFFFF,
}
And want to know whether a given value is part of the enum and used Enum.TryParse
but with the following Code it will always return true even 1 is not part of the enum:
Enum.TryParse<SomeEnum>("1", out _);
Thats because the following line does not corse an error:
var myEnum = (SomeEnum)1;
So I´ve changed to the Method Enum.IsDefined
, so far so good the following code does deliver the desired results:
Enum.TryParse<SomeEnum>(myValue, out var x) && Enum.IsDefined(x);
But now the edge case is:
var myEnumValue = uint.Max;
Enum.TryParse<SomeEnum>(myValue.ToString(), out var x) && Enum.IsDefined(x);
Which delivers true because x = SomeEnum.Unknown
and thats caused because IsDefined
does a cast to ushort
from uint.Max
which is 0xFFFFFFFF
to 0xFFFF
. So I do not know how to check for any case whether a numeric value is part of a given enum.