Choose Function

   
Choose Function

Class

Microsoft.VisualBasic.Interaction

Named Arguments

No

Syntax

 Choose(   index, item_1[,item_2, ...[, item_n]]   ) 
index (required; Single)

An expression that evaluates to the (1-based) index of the object to choose from the list

item_1-item_n (required; any)

A comma-delimited list of values from which to choose, or a ParamArray containing values from which to choose

Return Value

The object chosen from the list.

Description

Programmatically selects an object from a predefined list of objects (which are passed as parameters to the function) based on its ordinal position in the list. Using Choose is a simpler alternative to populating an array with fixed values.

Rules at a Glance

  • The list of items is based from 1, rather than the more usual VB default base of 0.

  • Because the list consists of objects, you can mix data types within the list; you are not forced to use the same data type for each item in the list. For example, item_1 can be a string, while item_2 can be a long integer, and item_3 can be a floating point number.

  • If the rounded value of index does not correspond to an item in the list, the function returns a null string.

Programming Tips and Gotchas

  • If index is not a whole number, it is rounded before being used.

  • It is important to note that all items in the list are evaluated. Thus, if we use functions or expressions as parameters, all of the functions are called or all of the expressions are evaluated.

  • By providing item_1 through item_n in the form of a ParamArray, the list of values can be expanded or contracted programmatically at runtime.

  • You can save memory and create more efficient and self-documenting code by using the Choose function instead of creating an array and populating it with fixed values each time the program executes. As the following example illustrates, you can turn several lines of code into one:

     Dim vMyArray(3) vMyArray(1) = "This" vMyarray(2) = "That" vMyArray(3) = "The Other" ... Sub chooseFromArray(iIndex as Integer)     vResult = vMyArray(iIndex) End Sub Sub chooseFromChoose(sglIndex as Single)     vResult = Choose(sglIndex, "This", "That", "The Other") End Sub 

VB.NET/VB 6 Differences

  • In VB 6, item_1 through item_n must only take the form of a comma-delimited list. In VB.NET, these arguments can also take the form of an array. This allows the list of choices to be modified dynamically at runtime.

  • In VB 6, idx must be greater than .5 and less than .5 plus the number of items in the list, or a runtime error results. In VB.NET, if idx is out of range, the function returns a null string.

See Also

Switch Function

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net