XTab's Blog

Ged Mead's Blog at vbCity

This blog hosted by:
http://blogs.vbcity.com      
  Home :: Syndication  :: Login

JunJuly 2008Aug
SMTWTFS
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

Archives

Topics

Ramblings

VB.NET

Sunday, July 06, 2008 #

  I never cease to be amazed at how many ways you can fool yourself into thinking that your code will do one thing, but in fact it does something completely different. Sometimes the subtlety of the error is so fine that you can spend ages trying to work out the source of the problem and, to make life harder, there's no Exception message to give you a pointer and sometimes even using the debugging tools doesn't lead you straight to it.

  I was working on something that kept track of a particular value. If the value was between 31 and 40 then I wanted to display a message. Without thinking too hard about it, I wrote the following code:

Code Copy
Select Case InputValue
            Case 31 - 40
                MessageBox.Show("Invalid Values")
            Case Else
                '  Do something
End
Select

   So, what do you think? Will this do the job as described?

  Actually, no - of course not; otherwise I wouldn't be sat here writing about it, would I? The question is then: What's wrong with it? On the face of it, it seems to check for values between 31 and 40, displaying a message if that case fits. Otherwise, it does something else. But if you were to try this code and enter values between 31 and 40 you wouldn't get to see that MessageBox.

  It's one of those Duh! moments as soon as you realise why. Although most of us will have read that as saying "Case 31 to 40" , that isn't how the compiler sees it. Because we are dealing with numbers and because the compiler knows about adding and (in this case most importantly) subtracting .... the compiler reads that as "Case 31 minus 40. So the MessageBox will only appear if a value of -9 is applied to the InputValue variable.

  It's not a compilation error, so you don't get any feedback. It's allowable but faulty syntax, so you're not alerted to what is essentially a logic mistake.

  So simple when you realise why, but it's another example of those tricky little Gotchas that'll get ya if you don't watch out!

posted @ 5:22 PM | Feedback (1)