Tarik
Tarik

Reputation: 81801

Find Enum Value by Passed Parameter

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.

Upvotes: 2

Views: 916

Answers (2)

Mike Valenty
Mike Valenty

Reputation: 8991

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));

Upvotes: 2

dtb
dtb

Reputation: 217401

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.

Upvotes: 5

Related Questions