Click here to Skip to main content
14,869,969 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Updated 8-Dec-19 9:14am

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.
[no name] 26-Feb-13 12:57pm
Hi, actually I think most values in my enum types are 'int's...
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;

[no name] 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 ...
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.

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

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900