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 Choose function

Total Hit ( 2935)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


The Choose function lets you often make more concise, albeit not faster, code, because it lets you replace a lengthy Select Case block. For example, the following code:

Click here to copy the following block
Select Case index
  Case 1
    result = 100
  Case 2
    result = 250
  Case 3
    result = 400
  Case 4
    result = 500
End Select

can be replaced by the more concise:

Click here to copy the following block
result = Choose(index, 100, 250, 400, 500)

If the index is less than one or higher than the number of values, the Choose function returns Null. Here's another way to use the Choose function in place of a If...ElseIf block:

Click here to copy the following block
' the standard way
If x < y Then
  result = 100
Elseif x = y Then
  result = 150
Else
  result = 400
End If

' the more concise way
result = Choose(Sgn(x - y) + 2, 100, 150, 400)

Finally, the Choose function is often useful to quickly initialize an array of number or strings:

Click here to copy the following block
' the standard way
Dim names(1 To 5) As String
names(1) = "Robert"
names(2) = "Patrick"
names(3) = "Timothy"
names(4) = "James"
names(5) = "Frank"

' the more concise way
Dim names(1 To 5) As String, i As Integer
For i = 1 To 5
  names(i) = Choose(i, "Robert", "Patrick", "Timothy", "James", "Frank")
Next

It is evident that the more array elements you must initialize, the more code you save using this technique.
However, in all cases you should keep in mind that the Choose function is always slower than the Select Case or If block it is meant to replace, therefore it shouldn't be used in time-critical loops.



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.