You're bound to be unhappy if you optimize everything. --Donald Knuth

Convert Integer To Enum Instance in C#

Copyright © 2011 Steve Lautenschlager

Enums are a powerful construction in C# and other programming languages when you are working with finite sets such as fruits, days of the week or colors. Visual Studio's Intellisense is very nice with Enums because it lists all the options for the programmer to choose from.

But quite often you want to print enums, compare int values, or serialize an enum--and then you have to do some conversions.

The following method may be run in the code-behind file of an ASPX page where you have added a Label control named lblOutput. However, this technique will work in any C# program, not just ASP.NET.

Example: Convert integer to Enum instance
public void EnumInstanceFromInt()
   // The .NET Framework contains an Enum called DayOfWeek.
   // Let's generate some Enum instances from int values.

   // Usually you wouldn't cast an instance of an existing Enum to an int
   // in order to create an Enum instance.  :-)  You would have the actual
   // integer value, perhaps a value from a database where the int value of
   // the enum was stored.

   DayOfWeek wednesday = 
      (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), (int)DayOfWeek.Wednesday);
   DayOfWeek sunday = 
      (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), (int)DayOfWeek.Sunday);
   DayOfWeek tgif = 
      (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), (int)DayOfWeek.Friday);

   lblOutput.Text = wednesday.ToString() 
      + ".  Int value = " + ((int)wednesday).ToString() + "<br>";
   lblOutput.Text += sunday.ToString() 
      + ".  Int value = " + ((int)sunday).ToString() + "<br>";
   lblOutput.Text += tgif.ToString() 
      + ".  Int value = " + ((int)tgif).ToString() + "<br>";


The Enum.ToObject method takes two arguments. The first is the type of the enum you want to create as output. The second field is the int to convert. Obviously, there must be a corresponding Enum entry for the conversion to succeed.

Example: Output
Wednesday. Int value = 3
Sunday. Int value = 0
Friday. Int value = 5

Version: 6.0.20200920.1535