I have read 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’ ie 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 }
Thanks
Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy.
TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .
You need to cast the result to the actual array type you want
(Response[])Enum.GetValues(typeof(Response))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With