How to get Enum object by value in C#?

18,440

Solution 1

Why not use this build in feature?

ShipmentStatus shipped = (ShipmentStatus)System.Enum.GetValues(typeof(ShipmentStatus)).GetValue(1);

Solution 2

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.

Solution 3

After some battling with Enum I created this - a universal helper class that will do what I needed - getting key by value, and more importantly - from ANY Enum type:

public static class EnumHelpers {

  public static T GetEnumObjectByValue<T>(int valueId) {
    return (T) Enum.ToObject(typeof (T), valueId);
  }

}

So, to get Enum object ShipmentStatus.Shipped this will return this object:

var enumObject = EnumHelpers.GetEnumObjectByValue<ShipmentStatus>(1);

So basicaly you can use any Enum object and get its key by value:

var enumObject = EnumHelpers.GetEnumObjectByValue<YOUR_ENUM_TYPE>(VALUE);
Share:
18,440
mikhail-t
Author by

mikhail-t

Updated on June 14, 2022

Comments

  • mikhail-t
    mikhail-t almost 2 years

    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?

  • juharr
    juharr almost 11 years
    You might want to add a check to make sure the value is valid for the Enum. According the the documentation for Enum.ToObject it does not do that check. You can use Enum.IsDefined for that.
  • Alexander Bell
    Alexander Bell almost 11 years
    Exactly right! Otherwise, the conversion is just a line of code.
  • middelpat
    middelpat almost 11 years
    hmm didn't think about this. a lot shorter :)
  • Alexander Bell
    Alexander Bell almost 11 years
    Yeah, it's kinda "short-cut" :-)