In previous article, I have mentioned Converting String to Enum OR Enum to String in C# but in this article, I have mentioned how we can convert Int to Enum in C# or Enum to int in C#, quickly and easily using console application example.
Using Typecasting (Int To Enum)
We can convert int to Enum using typecasting in C#, so here is the simple console application example to do it.
using System;
using System.IO;
namespace IntToEnum
{
internal class Program
{
public enum Months
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
static void Main(string[] args)
{
int i = 2, j = 6, k = 11;
Months month1, month2, month3;
month1 = (Months)i;
month2 = (Months)j;
month3 = (Months)k;
Console.WriteLine(month1);//March
Console.WriteLine(month2);//July
Console.WriteLine(month3);//December
}
}
}
Output:
March
July
December
Using Enum.ToObject()
Method (Int to Enum)
Instead of using above Typecasting method, we can also use Enum.ToObject method of C# to convert int to enum, considering above example, if we use typecasting, then we will have to update below code
int i = 2, j = 6, k = 11;
Months month1, month2, month3;
month1 = (Months)Enum.ToObject(typeof(Months), i);
month2 = (Months)Enum.ToObject(typeof(Months), j);
month3 = (Months)Enum.ToObject(typeof(Months), k); ;
So complete console application code will look like below
using System;
using System.IO;
namespace IntToEnum
{
internal class Program
{
public enum Months
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
static void Main(string[] args)
{
int i = 2, j = 6, k = 11;
Months month1, month2, month3;
month1 = (Months)Enum.ToObject(typeof(Months), i);
month2 = (Months)Enum.ToObject(typeof(Months), j);
month3 = (Months)Enum.ToObject(typeof(Months), k); ;
Console.WriteLine(month1);//March
Console.WriteLine(month2);//July
Console.WriteLine(month3);//December
}
}
}
Output, is same as above.
March
July
December
Enum to Int in C#
If you want to convert Enum to Int or want to get int from Enum value, then we can again use typecasting in C# or use Enum.Parse or directlt Convert Enum to int using Convert.ToInt(), here is the sample console application.
using System;
using System.IO;
namespace EnumToInt
{
internal class Program
{
public enum Months
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
static void Main(string[] args)
{
Enum en = Months.February;
Console.WriteLine(Convert.ToInt32(en)); // 1
Console.WriteLine((int)(object)en); // 1
Console.WriteLine((int)Enum.Parse(en.GetType(), en.ToString())); //using Enum.Parse
Console.WriteLine((int)(object)en);
}
}
}
That's it, hope it helps.
You may also like to read:
Nested and Complex JSON Example
Generate Random alphanumeric strings in C#