Reputation: 51094
The following code returns One, Two, Three, where I expect GetNames to do that and GetValues to return 2, 5, 10:
enum Nums
{
One = 2,
Two = 5,
Three = 10
}
class Program
{
static void Main()
{
var vals = Enum.GetValues(typeof(Nums));
}
}
What is up here? How do I get the values 2, 5, 10 from the type Nums
?
Upvotes: 0
Views: 69
Reputation: 324
I haven't fully wrapped my head around C# Enums yet, but the Enum.GetValues documentation has an example that shows that casting has some very interesting and powerful effects on them. http://msdn.microsoft.com/en-us/library/system.enum.getvalues(v=vs.110).aspx
using System;
enum SignMagnitude { Negative = -1, Zero = 0, Positive = 1 };
public class Example
{
public static void Main()
{
foreach (var value in Enum.GetValues(typeof(SignMagnitude))) {
Console.WriteLine("{0,3} 0x{0:X8} {1}",
(int) value, ((SignMagnitude) value));
} }
}
// The example displays the following output:
// 0 0x00000000 Zero
// 1 0x00000001 Positive
// -1 0xFFFFFFFF Negative
Upvotes: 0
Reputation: 1114
You need to cast it to an int:
int val = (int)Nums.One;
Or to answer your question for getting all of the items in the enum:
IEnumerable<int> values = Enum.GetValues(typeof(Nums)).Cast<int>();
Upvotes: 1
Reputation: 726987
You can do it like this:
int[] vals = Enum
.GetValues(typeof(Nums)) // Thus far, this is your code
.Cast<int>() // Cast individual elements to int
.ToArray(); // Convert the result to array
Upvotes: 1