Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.GetValues() Return Type

Tags:

c#

enums

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

like image 991
Cragly Avatar asked Sep 09 '09 09:09

Cragly


People also ask

How to Get value from enum?

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.

What is enum method in c#?

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.

How do you convert a string value to a specific enum type in C#?

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 .


1 Answers

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.

like image 63
thecoop Avatar answered Oct 08 '22 13:10

thecoop