Enum = Integer prevention

  • Thread starter Thread starter Zytan
  • Start date Start date
Z

Zytan

Even with Option Strict On, which prevents an enum being set to an
Integer, you can still compare an enum to an integer without
complaint:

myEnum = 1 'fails
if (myEnum = 1) Then ... 'works

Is it possible to have strict type checking so strict that it prevents
all integer / enum interaction? I don't get why they would let this
one through.

Zytan
 
Hello

A enum is intended to make a more readable parameter construct where you
would have otherwise used numeric values as parameters
myEnum = 1 'fails cause it is a setter and this should be type casted
if (myEnum = 1) Then ... 'works cause it is a comparisation to the actual
numeric value of the enum wich is normally an 0,1,2,3,4,5, etc etc etc

regards

Michel
 
A enum is intended to make a more readable parameter construct where you
would have otherwise used numeric values as parameters

Yes, exactly. That's precisely what they are for. And this applies
to both cases:
1.
myStatus = 1 'bad code, illegal code
myStatus = InitiaitionStatus 'good code

2.

If myStatus = 1 Then 'bad code, LEGAL code
do_something()
Endif
If myStatus = InitiaitionStatus Then 'good code
do_something()
Endif

Michel, i fail to follow this logic. You are simply explaining the
semantics of the language. so, yes, i understand that it doesn't
allow 'setting' but allows 'comparison'. But your words do not
explain any reason as to why the language is this way. In fact, your
first paragraph shows exactly why it shouldn't be this way.

But, thanks, because i think you have answered my original concern
that VB doesn't have complete strict type checking. (I assume there's
no way to force it to be so?)

This is sad, since, say, in the case of converting a variable that
stores a 'stage / status' as 0, 1, 2, etc. into an Enum, you cannot
rely on the language to find anything missed. I think it's a shame.
But, at least they did the half that was implemented, and its better
than nothing. i was just getting my hopes up that it was perfect.

Incidentally, for those that think i am being picky, i've already seen
MSDN tutorials on VB .NET that have mistakes since they are allowed to
use Integers for Enums, where if they had been forced to use the Enum,
the mistake would have been caught (and the example would have been
much easier to learn).

Zytan
 
Back
Top