There are two ways to write error-free programs; only the third works. --Alan J. Perlis
Welcome to my blog about software development and the Microsoft stack.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

Subscribe for news, updates and more:

Leaves on Water - 11/2011. Copyright © Steve Lautenschlager.

Convert Integer To Enum Instance in C#

By steve on January 09, 2007.
Updated on January 01, 2012.
Viewed 231,003 times (66 times today).
Article TypesLanguage ElementsLanguage ElementsLanguagesTechnologies
SnippetConversionsEnumsC#.NET

Summary

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
Back to Top

User Comments (14)

Posted 2007 Mar 30 08:22 AM. reply
This does not make things clear. Please smaller steps. Convert from A to B. Not from A to B via C, back to A.

Yoho
Reply 2007 Mar 30 20:19 PM by steve. reply
Hi Yoho, Sorry if this was too much. I don't believe it can get much simpler, but I'll try. This is about the simplest I can make it:

 Type enumType = typeof(DayOfWeek);
 DayOfWeek day = (DayOfWeek)Enum.ToObject(enumType, 0);
Replied 2007 Jun 14 14:54 PM by Deepak Reddy. reply
This is the simplest one I guess.

DayOrWeek day = (DayOfWeek)0;

thats it :)
Replied 2007 Jun 14 15:19 PM by Brent. reply
What is the difference between this and the code below, if any?

 (DayOfWeek) day = (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), 0);
 
Replied 2008 Nov 21 06:18 AM by Ramveer. reply
Thanks This is very good answer.
Posted 2007 Apr 20 07:21 AM. reply
You're converting Enums to Integers instead of what the topic says.

My Name
Reply 2007 Apr 20 20:53 PM by steve. reply
I'm doing both int to Enum and Enum to int. However, the enum to int is quite easy, it's just a type cast, and the reason I do that instead of entering a plain int is so you can see which item in the enum the int corresponds to and then prove to yourself that after the conversion you have the correct enum.
Replied 2007 Jun 21 08:52 AM by Peter. reply
Still your article is quit confusing wat first glance.. Deepak Reddy's answer could be put on top of the page for all those people (=me) that are just looking for a quick and simple example.. Nonetheless thank you for posting.. :) !
Posted 2007 Jul 18 14:09 PM. reply
Here is the generic convert for Enum type

public static class Convert
{
 public static T EnumTypeTo<T>(object value)
        {
            Type conversionType = typeof(T);

            if (!conversionType.IsGenericType && conversionType.IsEnum)
            {
                return (T)Enum.ToObject(conversionType, value);
            }

            try
            {
                return (T)Convert.ChangeType(value, conversionType);
            }
            catch
            {
                return default(T);
            }
        }

}
Usage examples: 1. Convert to Integer

int iWed = Convert.EnumTypeTo<int>(DayOfWeek.Wednesday);
2. Convert to String

string sWed = Convert.EnumTypeTo<string>(DayOfWeek.Wednesday);
and now back to Enum Instance from string/int

DayOfWeek wednesday = Convert.EnumTypeTo<DayOfWeek>(sWed);
DayOfWeek wednesday = Convert.EnumTypeTo<DayOfWeek>(iWed);
Hope this help!!!!

Kimuyen Hoang
Posted 2007 Sep 27 16:45 PM. reply
Obviously, there must be a corresponding Enum entry for the conversion to succeed.


Actually that is not true. You can convert any integer value to an enum. However you can check value against an enum before casting using Enum.IsDefined. See http://dotnettipoftheday.org/tips/validate_before_cast_enum_isdefined.aspx

manovich
Posted 2010 Sep 14 22:06 PM. reply
This is a nice little article - I have it bookmarked as its one of those not-so-obvious C# thingies. I tend to do this:

public DayOfWeek GetDayOfWeek(int as DayValue)
{
	if (Enum.IsDefined(typeof(DayOfWeek), DayValue))
	{
		return (DayOfWeek)DayValue;		
	}
	else
	{
		throw new Exception("WaWaOoops!");
	}
}
I always wonder if (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), DayValue) actually does two casts EnumItem ==> Object ==> Int or if the compiler is cleaver enough to just do the one (it would be virtual anyway I guess as 'Object' is the base object anyway).

Richard
Posted 2011 Jun 20 07:19 AM. reply
great article. It was very help full for me.

Ruwan
Posted 2011 Nov 09 10:04 AM. reply
Thanks. This article saved me some time. Thanks also to Kimuyen!

FathomSavvy
Posted 2012 Mar 24 21:14 PM. reply
Thanks for this article. Very good.

Juan Ramirez
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.