Click to See Complete Forum and Search --> : Puzzled: cannot cast int to enum:int in CLI?!?!?


avatar.ds
July 16th, 2006, 10:16 AM
This seems very strange to me but I can't cast an integer to an integer-based enum in c++/cli.
Consider this:

enum Currency : int
{
Currency_USDollar = 0,
Currency_EUEuro = 1,
};

ref class Test
{
void CycleCurrencies()
{
for(int C = 1; C>0; C--)
{
DoSomethingWithCurrency(Currency(C));
DoSomethingWithCurrency(static_cast<Currency>(C));
DoSomethingWithCurrency(safe_cast<Currency>(C));
};
};
void DoSomethingWithCurrency(Currency _Currency) //
{ Currency C = _Currency; }; // "UNDEFINED VALUE?!?!?!?!?"
};

This code does not work no matter which casting I use! Also, when watched from the debugger, it shows "undefined value" for the cast enums.

What am I doing wrong here? It's such a basic stuff for c++, I'm amazed I ran into this curious problem.

avatar.ds
July 17th, 2006, 02:47 PM
Solved the problem. The convertion does work, but the watch doesn't. This was a hindrance to finding the error in my code.

darwen
July 17th, 2006, 04:43 PM
Casting enums to ints and vice-versa in .NET is really dangerous, and considered bad practice.

Enums in .NET are considered their own entities and are only maintained as integers for backward compatibility with C and C++ (I wish they weren't).

You should have a map (i.e. a Hashtable) between the integer value and the enum to do any conversions you need to do.

But really, enums are their own type and should be considered as such.

Darwen.