why enum members need conversion

N

Nikhil Patel

Hi all,
I am a VB6 programmer and learning C#. I am currently reading a chapter
on types. I have question regarding enums. Why do we need to convert enum
members to the value that they represent?

Thanks in advance...

-Nikhil
 
N

Nikhil Patel

Thanks for the reply.
I think I didnt give more details on my question. Let me give an
example:

public enum Numbers
{
zero=0,
one=1,
two=2
}

now if I want to use Numbers.two in mathematical calculations, I need to
explicitly convert it to int as follows,

MessageBox.Show(((int)Numbers.two * 2).ToString()); //Displays 4

But if we use the Numbers enum in switch statement, we dont have to convert
it.

So my question is why do we have to convert the members in some cases.
VB.Net does not require the implicit conversion of the enum numbers even if
you use them in mathematical calculations.

Thanks...

-Nikhil
 
R

rubber21

why? why?

SECURITY man. More RULES. RED TAPE. Or incapacitation if you look closer.
Don't enter the MATRIX! Don't lose your freedom! Stay with VB or better jump
to C++ if you want to know what FREESTYLE is.

open your eyes!
 
J

Jon Skeet

[If this post comes through twice, but with a different last sentence,
take this one as the more correct one :) ]

Nikhil Patel said:
I am a VB6 programmer and learning C#. I am currently reading a chapter
on types. I have question regarding enums. Why do we need to convert enum
members to the value that they represent?

Type safety, basically. You have to prove to the compiler that you
really know that the variable in question is an enum and not an int,
but that in this case you want to treat it as an int, or vice versa.

Sometimes it gets in the way, other times it's useful.
 
J

Jay B. Harlow [MVP - Outlook]

Nikhil,
Learn to use Option Strict On in VB.NET! :)

With option strict on VB.NET does require the explicit conversion of enums,
to perform math. The only 'math' operator defined for Enum types in VB.NET
is the Or operator to combine Enums that have the Flags attribute applied
for example. Of course you can compare two Enums and assign an Enum also.

You should normally use Option Strict On at the top of each of your VB.NET
files, to ensure compile time errors over run time errors. As Jon Skeet
stated, type safety!

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top