RobLog

Web Design in the World of .NET (C# and VB.NET, XML, and Javascript). I learned how to program from TheDailyWTF.com!
posts - 140, comments - 129, trackbacks - 5

My Links

News

Main Site Cert Corner Goals About Me

Article Categories

Archives

Post Categories

Image Galleries

.NET

Personal

WOW


Here's a fun fact... Enumeration Comparison to Integer

Visual Basic 2005 (& VB.NET 2003) Hard Lesson #1 : Enumeration Comparison to Integer with Option Strict On

Let's say you use Option Strict in VB.  If you use an enumeration, you have to explicitly cast it if you are going to compare the value to an integer based value, but the compiler will not tell you that.  If you put the information in the watch window or the immediate window, it looks like it is evaluating to true, but it is not.

Let's explore this, shall we?

Dim intArray() As Integer = {myEnumeration.ValueOfZero,myEnumeration.ValueOfOne,myEnumeration.ValueOfTwo}  ' becomes {0,1,2} implicitly

Dim visible As Boolean = (Not Array.IndexOf(intArray, myEnumeration.ValueOfOne) = -1)  ' does not implicitly cast the enumeration value to it's integer value, thus evaluates to false, turn off Option Strict and it will evaluate to true

visible = (Not Array.IndexOf(intArray, CInt(myEnumeration.ValueOfOne)) = -1)  ' correctly evaluates to true

Both property settings (for visible) look almost exactly the same, and you would expect the same results.  Both should evaluate to True, but the first one evaluates to false.  The precompiler and the compiler do not warn you of this error like they should.  We would like to call this a bug, because it is definitely unexpected behavior.  Do you see what is causing the problem?  Creating the array as an integer, instead of the enumeration type.  What you should do instead is:

Dim enumerationArray() As myEnumeration = {myEnumeration.ValueOfZero,myEnumeration.ValueOfOne,myEnumeration.ValueOfTwo} 

 

This still doesn't account for the fact that this is still a bug that should be evaluated by Microsoft. Why? I don't believe the watch windows or the immediate window make use of Option Strict even when you use it in the project. So it will look like the example is evaluating to true everywhere but in the running code.  Therefore, although I would never recommend a developer coding like the above example, there is potential for someone to look at this and not catch the error for a long time because it will look like it is evaluating to True to someone debugging the code.

UPDATE: We have verified that this behavior exists in the VB.NET 2003 Compiler as well.

UPDATE: I submitted a bug report to Microsoft:  http://lab.msdn.microsoft.com/ProductFeedback/viewfeedback.aspx?feedbackid=f621e36b-7ddb-42a9-89e5-d0e84e4d237d&lc=1033

posted on Tuesday, February 28, 2006 11:07 AM