Fetch Random Item from Array

Description: Generic function for choosing a random item from a single dimension array of items and returning it.
Tested Platform: .NET 4.8, Visual Studio 2022, Windows 10
Language: VB.NET
' Generate a random number based on the upper and lower bounds of the array, then use that to return the item.           

Public Function FetchRandomItem(Of t)(ByRef theArray() As t) As t
    Dim randNumberGenerator As New Random

    Dim index As Integer = randNumberGenerator.Next(theArray.GetLowerBound(0), theArray.GetUpperBound(0) + 1)

    Return theArray(index)
End Function

Posted: March 20, 2023

Return to the snippets listing