Select Case

Posted Thu, Apr 27 2006 11:51 by bill
VB really has a very cool Select Case set of features, features that other languages with their
 
childish switch blocks can only today dream of.  For example, did you know you could do this in Vb ?
 
Select Case myAge ' myAge is an Int32
  Case  42
    'totally awesome !
  Case 41, 43
    '
  Case 44 To 100
    '
  Case Is < 40, Is > 100
End Select
 
in the above I've shown at least 3 special features.
you can use comma separated values on a single Case statement (e.g. 41,43)
you can use range statements like 44 To 100
you can use Is with a relational operators such as Is < 40
You could also combine any of those in a single case statement, such as :
 Case Is < 40, 42, 50 To 60, Is > 100
 
Pretty cool huh ?
 
So what doesn't Select Case do (other than not make coffee) ?  Well it doesn't work well when it comes
 
to reference comparison or TypeOf comparisons.  For example you might want to see if "sender" in an
 
event handler is menuItem1 or menuItem2.  Or in a treeview's selected node event, if you have custom
 
nodes you might want to check what type that node is.
Well today the only way of doing that with Select Case is so ugly, I'm not going to even show it (it
 
involves using Select Case True).  The problem with adding this functionality is we have to look after
 
the goodness we already have.   Let's take the menuItem example. If we were to have code like:
 
Select Case sender
   Case Is menuItem1
     …
We have changed the meaning of "Is" in a select case.  As I showed in the first example, Is is really
 
a placeholder for the test expression "sender".   This would make code correction and help topics more
 
complex.  The proper syntax would probably be:
 
Select Case sender
   Case Is Is menuItem1
     …
But that just looks like you've got a stuttering problem.
Another issue with these two syntaxes is they make it look like you could also have cases where the Is
 
(or Is Is) is not required, yet clearly you couldn't.
 
Okay, drumroll…….. Here's the syntax I would like to see:
 
Select Case sender Is
  Case menuItem1
     …
  Case meuItem2
     …
End Select
 
and :
 
Select Case TypeOf node Is
   Case FileNode
      …
   Case FolderNode
     ..
End Case
 
So the syntax rules for Select Case <expression> would become
 
Select Case <expression>|<partial referential expression>
 
Where <partial referential expression> is either:
 TypeOf <objExpression> Is
Or
   <objExpression> Is
 
Filed under: , ,