Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Enum object by value in C#?

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?

like image 841
mikhail-t Avatar asked May 09 '13 14:05

mikhail-t


2 Answers

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.

like image 129
Alexander Bell Avatar answered Sep 20 '22 20:09

Alexander Bell


Why not use this build in feature?

ShipmentStatus shipped = (ShipmentStatus)System.Enum.GetValues(typeof(ShipmentStatus)).GetValue(1);
like image 25
middelpat Avatar answered Sep 17 '22 20:09

middelpat