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.0, Visual Studio 2010, Windows 7
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

Submitted: October 22, 2012

Return to the snippets listing