CSharp - Enum Enum Conversions

Introduction

There are three ways to represent an enum value:

  • enum member defined in the enum
  • its underlying integral value
  • A string

Here is how to convert between each.

Enum to integral conversions

An explicit cast converts between an enum member and its integral value.

An explicit cast is the correct approach if you know the enum type at compile time:

[Flags] public enum Directions {
   Left=1, Right=2, Top=4, Bottom=8
}

int i = (int) Directions.Top;            // i == 4
Directions side = (Directions) i;       // side == Directions.Top

You can cast a System.Enum instance to its integral type in the same way.

First cast to an object, and then the integral type:

static int GetIntegralValue (Enum anyEnum)
{
       return (int) (object) anyEnum;
}

To write a method that works with an enum of any integral type, you can take one of three approaches.

The first is to call Convert.ToDecimal:

static decimal GetAnyIntegralValue (Enum anyEnum)
{
       return Convert.ToDecimal (anyEnum);
}

The second approach is to call Enum.GetUnderlyingType in order to obtain the enum's integral type, and then call Convert.ChangeType:

static object GetBoxedIntegralValue (Enum anyEnum)
{
       Type integralType = Enum.GetUnderlyingType (anyEnum.GetType());
       return Convert.ChangeType (anyEnum, integralType);
}

The third approach is to call Format or ToString specifying the "d" or "D" format string.

This gives you the enum's integral value as a string, and it is useful when writing custom serialization formatters:

static string GetIntegralValueAsString (Enum anyEnum)
{
       return anyEnum.ToString ("D");      // returns something like "4"
}

Demo

using System;

[Flags]/*from   www .  jav  a 2  s  .  c  o  m*/
public enum Directions
{
    Left = 1, Right = 2, Top = 4, Bottom = 8
}


class MainClass
{
    public static void Main(string[] args)
    {
        int i = (int)Directions.Top;            // i == 4
        Directions side = (Directions)i;       // side == Directions.Top

        Enum anyEnum = Directions.Top;
        Console.WriteLine(anyEnum);

        i = GetIntegralValue(anyEnum);
        Console.WriteLine(i);
    }

    static int GetIntegralValue(Enum anyEnum)
    {
        return (int)(object)anyEnum;
    }

}

Result

Integral to enum conversions

Enum.ToObject converts an integral value to an enum instance of the given type:

object bs = Enum.ToObject (typeof (Directions), 3);
Console.WriteLine (bs);                          

Related Topics

Quiz