Question
Say I have enum as follows (taken from MSDN example):
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
I can then use is in the code as follows:
int today = (int)Days.Sun;
Question:
Can I evaluate enums? Say I have a variable Day whose value is "Sun". Will Days.Day evaluate to Days.Sun?
Thanks!
Please don't get hung up on the days example and tell me I should use comparison etc...i am looking to replace the usage of arrays with enums as it is more compact. So what I am looking for is essentially an ability to retrieve values from enum similar to an array:
myArray[Day] where day will evaluate to array key....
Solution
Am I right in saying you've got:
string day = "Sun";
and you want to get back the value Days.Sun
?
If so, use:
string day = "Sun";
Day day = (Day) Enum.Parse(typeof(Days), day);
OTHER TIPS
Yes, you can do that. You can freely cast between an enum
and its underlying type.
using System;
class Program
{
static void Main()
{
// prints "zero"
Console.WriteLine((Foo)0);
// prints "1"
Console.WriteLine((int)Foo.one);
}
}
enum Foo { zero, one, two };
You can also parse the string values as well. Using Enum.Parse
[TestFixture]
public class EnumParsingSO
{
public enum Days
{
Sat = 1,
Sun,
Mon,
Tues
}
[Test]
public void EnumFromString()
{
Days expected = Days.Mon;
int expectedInt = 3;
Days actual = (Days)Enum.Parse(typeof(Days), "Mon");
Assert.AreEqual(expected, actual);
Assert.AreEqual(expectedInt, (int)actual);
}
}
As Andrew says, you can cast from an enum to its underlying type. You can also unbox between the two as well, and there's an implicit conversion from the constant 0 to any enum type:
using System;
enum Demo { Foo, Bar, Baz };
class Test
{
static void Main()
{
int i = 2;
object o = i;
// Unboxing from int to Demo
Demo d = (Demo) o;
Console.WriteLine(d);
o = Demo.Baz;
// Unboxing from Demo to int
i = (int) o;
Console.WriteLine(i);
// Implicit conversion of 0
d = 0;
Console.WriteLine(d);
}
}
for int yes , but for string you should do something like this
Yes you can, you just need to provide the native integer value for each enum value. From your example:
enum Days {
Sat=1,
Sun=2,
Mon=3,
Tue=4,
Wed=5,
Thu=6,
Fri=7
};
(Now, why you would order days of the week in this way is beyond me...)