Home
VB.NET
Choose Function Example
Updated Nov 16, 2022
Dot Net Perls
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.
Double
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.
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.
Nothing
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen