VB.NET Choose Function (Get Argument at Index)Demonstrate the Choose Function and understand the purpose of Choose.
Choose selects an element from several choices. It is available in the VB.NET programming language. The Choose function provides a utility procedure for returning one of the arguments as the choice.
This program introduces the Choose function and uses it. In the first part, we call Choose with 5 arguments: a double and 4 string literals. The value 3 indicates we want the third element. The value "Perls" is returned.DoubleStrings
Next: In the second usage of the Choose function, we use the Random type to randomly select one of the arguments to Choose.Random
Info: The arguments to Random.Next are inclusive and exclusive, so we pass 1 and 4. Choose returns a random element of the 3 that were passed.
Array: Instead of specifying the arguments to Choose directly, you can encapsulate them in an array type.
And: This makes for more extensible code. You can add as many elements as you want to the array and then choose from them.
VB.NET program that uses Choose function
' Get the third choice in the list of choices.
Dim result As String =
Choose(3, "Dot", "Net", "Perls", "Com").
' Get a random choice from the three choices.
Dim rand As Random = New Random()
Choose(rand.Next(1, 3 + 1), "Visual", "Basic", "NET").
How is the Choose function implemented in the .NET Framework internals? The method first converts the double type argument to an Integer. Then it validates the Choice array. And finally it returns the array element directly.
Also: It will return Nothing if you pass an index that is out of range. This is a null value.Nothing
Summary. We looked at 2 ways to use the Choose function. In many cases, it would be sufficient to use array subscripts. The Choose function could be useful to ensure that the subscript does not throw an exception due to being out of range.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.