How to cast an int to it's corresponding enum item?

Posted on 2004-03-24
Last Modified: 2012-05-04
I'm using an enum and also a class with public constants that were developed by two different people. Obviously, those two people didn't talk to each other and they implemented to same values using different integer values. For example, the enum looks like this:
public int WeekDaysEnum { Monday=0, Tuesday=1, Wednesday=2, Thursday=3, ...}

and the class looks like this:
public class WeekDaysClass {
     public const int Thursday=1;
     public const int Monday=5;
     public const int Wednesday=8;
     public const int Tuesday=10;

There is not direct relationship between the integer values of the items and they are listed in different orders but logically the "Monday" enum is equal to the "Monday" constant.

When I read the data from a database field, I get the integer corresponding to the class constant but I need to call a method which accepts a parameter of type WeekDaysEnum. So my question is:  how do I convert the the integer I read from the database into it's corresponding enum item? For example, how do I convert the value 5 into WeekDaysEnum.Monday?
Question by:FrenchJericho
  • 3
  • 2
  • 2
  • +2
LVL 23

Expert Comment

ID: 10673595
Simply use an int-int map.
LVL 14

Expert Comment

ID: 10673598
I don't think you can do this via a cast, you will have to write a simple mapping function, or create a Map to do the mapping, or even use an array to do the mapping.

For example, create an array of WeekDaysEnum, and fill the corresponding array location using the class constant with the enum.

For example ( this is semi-pseudo code)

WeekDaysEnum weekDaysConstantToEnum[20]; // whatever the max class constant is +1
weekDaysConstantToEnum[WeekDaysClass::Thursday] = WeekDaysEnum::Thursday;
weekDaysConstantToEnum[WeekDaysClass::Monday] = WeekDaysEnum::Monday;

Then you can just use the array to do the mapping

int day = ... // some way to get the day as a class constant
WeekDaysEnum enumday = weekDaysConstantToEnum[day];


Expert Comment

ID: 10675039
Well i recomended you at use

#define Monday         1
#define Tuesday        2
#define Wednesday    3
and so on.. just identify item.

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

LVL 30

Expert Comment

by:Mayank S
ID: 10675069
>> #define Monday         1

The source looks more like a Java code so I don't think that C/ C++ syntax would be helpful here.

Expert Comment

ID: 10675300
Very well C# looking,too =)

ok. Maybe the better choice then is use Package java.util List collection (inside Collections)
Just simple ordered list where index 1 = monday and so on...

indeed, there are many way at to do tihs ... upper mentioned Map collection, memory resident XML and so on...  
LVL 30

Expert Comment

by:Mayank S
ID: 10675382
>> Very well C# looking,too =)

Yes, could be. C# has almost the same syntax ;-)

Author Comment

ID: 10679644
Sorry I forgot to mention: it's C#.  

I thought about using a Hashtable to implement something similar to what wayside is suggesting but there are so many items that it would be a pretty big  (I used the days of the week to describe my problem in an effort to keep it simple, but my real scenario has more than 40 differnt items). I was hoping, since the integer value corresponds to the class constant value and since the constant 'name' corresponds to the enum item 'name', that there would be a way to transform the integer into the corrsponding class constant first, and then transform this constant into the corresponding enum item. I was hoping there was a way to do this using reflection maybe????

Am I day dreaming???? or is my only solution is to create this big hashtable and hard code which value corresponds to which? By the way, if I choose this approach and, at a later time, I need to do the conversion from an enum item to the class constant (which is the inverse of what I am currently trying to accomplish), does that mean that I will have to create a second big hashtable to create the inverse mapping???? You can see how this can become a nightmare to maintain if there are 40-50 items in each hashtable!!!!!!
LVL 14

Expert Comment

ID: 10680428
I don't know of any way to correlate two variables based on the variable name, or a piece of it. I think you will have to set up the mapping by hand and maintain it by hand. Sorry. :(

I think you only need one hashtable, but to go the other direction you will have to write a function to search the whole table element by element until you find a match. If you need to do this a lot you might be better off creating the second table.

It shouldn't be a big deal to set up the map, it's just pairs of values:

enumMonday, constantMonday
enumTuesday, constantTuesdays

As long as the names have something in common its easy to make sure they are correct.

Author Comment

ID: 10688416
Anybody knows of a general purpose class that will help me do that? A class capable of accepting pairs of objects (any type) and allow me to search

SearchClass objSearch = new SearchClass();
objSearch.Add(WeekDaysEnum.Monday, WeekDaysClass.Monday);
objSearch.Add(WeekDaysEnum.Tuesday, WeekDaysClass.Tuesday);
objSearch.Add(WeekDaysEnum.Sunday, WeekDaysClass.sunday);

WeekDaysEnum obj1 = (WeekDaysEnum) objSearch.Search(WeekDaysClass.Tuesday);
WeekDaysClass obj2 = (WeekDaysClass) objSearch.Search(WeekDaysEnum.Tuesday);
LVL 14

Accepted Solution

wayside earned 250 total points
ID: 10688813
It's pretty easy to write your own. Create an array of ints, add function to add and two function to search:

public class dayMap {

   int [] enumtoClass;
   int mapsize;
   int last

  dayMap(int size) {
     mapsize = size;
     enumtoClass = new int[size];
     int i;
     for (i=0; i<mapsize; i++)
            enumtoClass[i] = -1;

  void Add(enumDay, classDay) {
       enumtoClass[enumDay] = classDay;

  WeekDaysClass Search(WeekDaysEnum enumday) {
  if (enumDay > mapsize-1)
     return -1;

   return enumtoClass[enumDay];

 WeekDaysEnum Search(WeekDaysClass classday) {
 int i;
 for (i=0; i<mapsize; i++)
    if (enum.class[i] == classday)
        return i;

  return -1;

This is not pure C#, but you get the idea.


Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
wordlen challenge 3 66
Arduino EDI - Programming language 3 89
Basic Java Case or If-Else statement... 3 50
Beginner to Unreal Engine 4 5 79
Here we come across an interesting topic of coding guidelines while designing automation test scripts. The scope of this article will not be limited to QTP but to an overall extent of using VB Scripting for automation projects. Introduction Now…
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now