Given the code below, is there any possiblity the int cast could throw an exception?
static void foo(Type typeEnum)
{
if (typeEnum.IsEnum)
{
foreach (var enumVal in Enum.GetValues(typeEnum))
{
var _val = (int)enumVal;
}
}
}
Yes, if the
enumbacking type is notint, like:This will throw. This is because the
enumvalues are boxes asobject, and you can’t cast ‘object’ to ‘int’ unless the contained value is actually an ‘int’.You could alleviate this by doing a
Convert.ToInt32()which will work for all backing types ofintor smaller:Or, if you want to assume
intand just be safer, you can check the underlying type of theenumlike:Alternatively, you could assume a type of
longif signed orulongif unsigned (you can have negativeenumvalues, but tend to be rarer):This is why it’s probably safer to make some assumptions and check them on the call. Anything you do to unbox the value has the potential of throwing or overflowing.
You could even go generic and have the user pass in the type they want to get out:
So you could invoke this:
Then if they get an exception, it falls on them to specify the right size type…