Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Write concise code with the Switch function

Total Hit ( 1774)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Many VB developers don't realize that the Switch built-in function can often save a lot of code. This function takes any number of (expr, value) pairs, it evaluates all expressions and return the value related to the first expression that is found to be True. Typically you can use a Switch function to replace a If...ElseIf block, as in:

Click here to copy the following block
' the standard way
If x = 0 Then
  result = 100
ElseIf x < y Then
  result = x
ElseIf x > y Then
  result = y
Else
  ' X = Y and X <> 0
  result = 200
End If

' the more concise code
' Note that the Else clause is rendered with a True constant
result = Switch(x = 0, 100, x < y, x, x > y, y, True, 200)

If no expressions in the list returns a non-zero value, the Switch function returns Null. If you want to avoid this, just use True for the last expression in the list, as in the above example.
It is important to note that the Switch function always evaluate all the arguments passed to it, so you get an error whenever any argument is invalid, for example:

Click here to copy the following block
' the following statement raises a "Division by Zero" error if Y=0
MsgBox Switch(x = 0, "X is zero", y = 0, "Y is zero", True, "X/Y = " & x / y)

You can use the Switch function to quickly evaluate the minimum and the maximum of three values:

Click here to copy the following block
' the minimum of n1, n2, n3
min = Switch(n1 <= n2 And n1 <= n3, n1, n2 <= n1 And n2 <= n3, n2, True, n3)

' the maximum of n1, n2, n3
max = Switch(n1 >= n2 And n1 >= n3, n1, n2 >= n1 And n2 >= n3, n2, True, n3)



Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.