How to get Enum object by value in C#?

mikhail-t picture mikhail-t · May 9, 2013 · Viewed 16.8k times · Source

I recently encountered a case when I needed to get an Enum object by value (to be saved via EF CodeFirst), and here is my Enum:

public enum ShipmentStatus {
  New = 0,
  Shipped = 1,
  Canceled = 2
}

So I needed to get ShipmentStatus.Shipped object by value 1.

So how could I accomplish that?

Answer

Alexander Bell picture Alexander Bell · May 9, 2013

This should work, either (just casting the int value to enum type):

int _val = 1;
ShipmentStatus _item = (ShipmentStatus)_val;

Beware, that it may cause an error if that enum is not defined.