As you know, converting an int to an enum is straightforward. Doing it generically with type/range checking isn't. I looked for a reusable example since this seems like a common situation but did not find a suitable one. If oneit exists, please let me know. Below is a C# extension method that encapsulates this behavior. Any feedback is welcome.
public static T ToEnum<T>(this int value)
{
Type type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException($"{type} is not an enum.");
}
if (!type.IsEnumDefined(value))
{
throw new ArgumentException($"{value} is not a valid ordinal of type {type}.");
}
return (T)Enum.ToObject(type, value);
}