what logic behind casting enum

  • Thread starter Thread starter Guest
  • Start date Start date
Hi,

My take is since enums are basically integers, you give the underlying
integer value a different meaning when you cast one enum to another.

Let's assume we have two enums:

enum Color
{
Red = 1,
Green = 2
}

enum Hand
{
Left = 1,
Right = 2
}

Now we have a variable:

Color c = Color.Red;

And we cast it:

Hand h = (Hand)c;

I think h will be equal to Hand.Left, because it corresponds to the same
integer value of 1, but this is indeed meaningless from the code readability
standpoint. An exception when it can be really useful and appropriate is
probably juggling with WinAPI enums when doing advanced P/Invoke.
 
I agree.

It can be applied to the case where to wrap a third party package.
Suppose the third party give

enum ThirdParty { thirdParty1, thirdParty2, thirdParty3}
I can define a enum MyOwn {myOwn1, myOwn2, myOwn3}

Now My enum can be exposed to my user. Internally I will cast my enum value
to the third party one and another way round.



Dmitriy Lapshin said:
Hi,

My take is since enums are basically integers, you give the underlying
integer value a different meaning when you cast one enum to another.

Let's assume we have two enums:

enum Color
{
Red = 1,
Green = 2
}

enum Hand
{
Left = 1,
Right = 2
}

Now we have a variable:

Color c = Color.Red;

And we cast it:

Hand h = (Hand)c;

I think h will be equal to Hand.Left, because it corresponds to the same
integer value of 1, but this is indeed meaningless from the code readability
standpoint. An exception when it can be really useful and appropriate is
probably juggling with WinAPI enums when doing advanced P/Invoke.

--
Sincerely,
Dmitriy Lapshin [C# / .NET MVP]
Bring the power of unit testing to the VS .NET IDE today!
http://www.x-unity.net/teststudio.aspx

Fei Li said:
Hi,

Whi can help to expain what logic is when I cast enum a to b?

Thanks
 
Back
Top