Choose Function ExampleCall the Choose Function with multiple string arguments and understand the purpose of Choose.
This page was last reviewed on Nov 16, 2022.
Choose. This function selects an element from several choices. It is available in the VB.NET programming language. It may be used in programs in this language.
A helper method. Choose() provides a utility procedure for returning one of the arguments as the choice. It is a helper method—it helps us access an array in a random way.
Example. This program first calls Choose with 5 arguments: a double and 4 string literals. The value 3 indicates we want the third element. The value "Perls" is returned.
Next In the second usage of the Choose function, we use the Random type to randomly select one of the arguments to Choose.
Info The arguments to Random.Next are inclusive and exclusive, so we pass 1 and 4. Choose returns a random element.
Detail 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.
Module Module1 Sub Main() ' Get the third choice in the list of choices. Dim result As String = Choose(3, "Dot", "Net", "Perls", "Com"). ToString Console.WriteLine(result) ' Get a random choice from the three choices. Dim rand As Random = New Random() result = Choose(rand.Next(1, 3 + 1), "Visual", "Basic", "NET"). ToString Console.WriteLine(result) End Sub End Module
Perls NET
Internals. How is Choose() implemented? It 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.
Summary. We looked at 2 ways to use the Choose function. The Choose function could be useful to ensure that the subscript does not throw an exception due to being out of range.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.