Click here to Skip to main content
15,891,951 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:

C#
itemID = (MyEnumType)results.value("itemID").toInt();


where itemID is of type MyEnumType-and right hand side is integer.
Posted
Updated 8-Dec-19 9:14am
v3

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.
 
Share this answer
 
v2
Comments
[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
C#
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();
}
 
Share this answer
 
v2
Comments
[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.
 
Share this answer
 

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