Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
Hi, is it ok to cast int to enum like this:
 
itemID = (MyEnumType)results.value("itemID").toInt();
 
where itemID is of type MyEnumType-and right hand side is integer.
Posted 25-Feb-13 21:40pm
Edited 25-Feb-13 21:52pm
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

For the compiler it is ok. Although you might want to familiarize yourself with C++11, which allows the definition of enums that are not int-based.
 
For good coding, it is not "ok", however: casting is almost always used as a cure for a bad choice of variable, function argument or function return type. Or else it may be a case of bad class design. If you can fix the function, variable or class to use a type that doesn't require casting, that will always be the preferred solution.
  Permalink  
v2
Comments
Matra Divat at 26-Feb-13 12:57pm
   
Hi, actually I think most values in my enum types are 'int's...
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

The answer is Yes. You simply can do it as follows
public enum  Country
{
    Bangladesh = 1,
    India = 2
}
 
public static void Main(string[] args)
{
    Country e = Country.Bangladesh;
 
    int x = (int) e;
 
    Country e2 = (Country) x;
 
    Console.ReadKey();
}
  Permalink  
v2
Comments
Matra Divat at 26-Feb-13 3:38am
   
My enum is declared somewhere separately in a .h file so I will just cast it I suppose also as you mentioned ...
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

This is one of the unfortunate features of enums. There is no elegant conversion from 'anything' to enum. The way you are doing it looks ugly but is pretty much the only way besides a big nasty switch() statement that duplicates all of the enum values.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web01 | 2.8.150302.1 | Last Updated 26 Feb 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100