You can explicitly type cast an int to a particular enum type, as shown below.
Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.
Use the Type Casting to Convert an Int to Enum in C# The correct syntax to use type casting is as follows. Copy YourEnum variableName = (YourEnum)yourInt; The program below shows how we can use the type casting to cast an int to enum in C#. We have cast our integer value to enum constant One .
IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
int i = 1;
Test val = static_cast<Test>(i);
Test e = static_cast<Test>(1);
Your code
enum Test
{
A, B
}
int a = 1;
Solution
Test castEnum = static_cast<Test>(a);
Spinning off the closing question, "how do I convert a to type Test::A
" rather than being rigid about the requirement to have a cast in there, and answering several years late only because this seems to be a popular question and nobody else has mentioned the alternative, per the C++11 standard:
5.2.9 Static cast
... an expression
e
can be explicitly converted to a typeT
using astatic_cast
of the formstatic_cast<T>(e)
if the declarationT t(e);
is well-formed, for some invented temporary variablet
(8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.
Therefore directly using the form t(e)
will also work, and you might prefer it for neatness:
auto result = Test(a);
Test castEnum = static_cast<Test>(a-1);
will cast a
to A
. If you don't want to substruct 1, you can redefine the enum
:
enum Test
{
A:1, B
};
In this case Test castEnum = static_cast<Test>(a);
could be used to cast a
to A
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With