Convert Enum to Integer or Integer to Enum examples | C# Examples
This tutorial explains about following things in C#
- How to convert Int to Enum constants
- How to parse Enum to Int in C Sharp?
Enum
is a custom special class type to have a group of constant values. the values can be strings or numbers.
Int
is a native predefined type in C# that stores numeric values.
Automatic conversion is not possible due to different types of data.
Let’s declare Enum constants in C#, Enum constants contain an int value.
public enum DAYS : int{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
Enum
in C# supports constants mapped with Integer, Short, Bytes, and String.
Above example, Enum constants map with an integer.
How to Convert Int to Enum in C#?
Sometimes, Integers values need to convert to Enum Constants.
Simply, cast an integer to a given type, returns Enum.
Enum enum = (Enum) integer ;
Here is an example for parse Int to Enum in C#
.
using System;
public class Program
{
public static void Main()
{
var day= (DAYS)2;
Console.WriteLine("Day is : {0}", day);
}
}
public enum DAYS : int
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
Output:
The day is : Tuesday
How to Parse Enum to Integer in F#?
It is easy to convert Enum to an integer using cast. Enum constant cast to int type as given below
int value = (int) Enum.constant;
Here is an example
using System;
public class Program
{
public static void Main()
{
int number = (int) DAYS.Friday;
Console.WriteLine("Day number is : {0}", number);
}
}
public enum DAYS : int
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
Compiled to output:
The day number is 5
Another way
- using Convert.ToInt32 function
DAYS day= DAYS.Friday;
int number = Convert.ToInt32(day);
- cast enum to an object, recast to an int type
DAYS day= DAYS.Friday;
int number = (int)(object)day;