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.
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.
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.
Random
type to randomly select one of the arguments to Choose.Random.Next
are inclusive and exclusive, so we pass 1 and 4. Choose returns a random element.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 ModulePerls NET
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.
null
value.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.