I have read the documentation that states that "given the type of the enum, the GetValues() method of System.Enum will return an array of the given enum’s base type" i.e. int, byte, etc.
However, I have been using the GetValues() method and all I keep getting back is an array of type Enums. Am I missing something?
public enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
foreach (var value in Enum.GetValues(typeof(Response)))
{
var type = value.GetType(); // type is always of type Enum not of the enum base type
}
You need to cast the result to the actual array type you want
as GetValues isn’t strongly typed
EDIT: just re-read the answer. You need to explicitly cast each enum value to the underlying type, as GetValues returns an array of the actual enum type rather than the base type. Enum.GetUnderlyingType could help with this.