tags:

views:

73

answers:

2

Hi,

I have an enum like this :

public enum Priority
{
   Low = 0,
   Medium = 1,
   Urgent = 2 
}

And I want to get the for example Priority.Low by passing like Enum.GetEnumVar(Priority,0) which should return Priority.Low

How can I accomplish that ?

Thank you in advance.

+4  A: 

Simply cast it to the enum type:

int value = 0;
Priority priority = (Priority)value;
// priority == Priority.Low

Note that you can cast any int to Priority, not only those which have a name: (Priority)42 is valid.

dtb
+2  A: 

Like this:

Priority fromInt = (Priority)0;
Assert.That(fromInt, Is.EqualTo(Priority.Low));

Also, this works:

Priority fromString = (Priority)Enum.Parse(typeof(Priority), "Low");
Assert.That(fromString, Is.EqualTo(Priority.Low));
Michael Valenty
Thanks, but I think Assert class is used for Unit Testing, you intended to verify its status ?
Braveyard
I ran the code in a unit test to make sure I didn't have a typo before I cut and pasted. I kept the Asserts because I think they communicate what I was trying to show. Similar to how dtb used the following comment: // priority == Priority.Low.
Michael Valenty