Select random objects from an array in C#

[Select random objects]

This example builds a generic extension method that lets you easily select random objects from an array. The following code shows the extension method and the RandomTools class that defines it.

public static class RandomTools
    // The Random object this method uses.
    private static Random Rand = null;

    // Return a random value.
    public static T PickRandom<T>(this T[] values)
        // Create the Random object if it doesn't exist.
        if (Rand == null) Rand = new Random();

        // Pick an item and return it.
        return values[Rand.Next(0, values.Length)];

The class first defines a private variable of type Random. It uses that object to generate random numbers when it needs them.

Next the class defines the PickRandom extension method. The <T> after the method’s name indicates that this is a generic method that takes one generic parameter that is called T within the method.

The this keyword indicates that this is an extension method that extends the variable that follows it. In this case, it extends an array of type T.

The method first checks the variable Rand and initializes it if it is null. The code then uses Rand.Next to generate a random number within the bounds of the array values. It finishes by returning the corresponding value from the array.

This code isn’t long, but it is a bit convoluted because it uses both extension methods and generics. After you define it, however, it’s very easy to use. The following code shows how the program uses the PickRandom method to pick a random line from the txtLines TextBox.

txtResult.Text = txtNames.Lines.PickRandom();

This code uses the txtNames control’s Line property to get an array containing the lines of text in the TextBox. It then calls the PickRandom method for that array and displays the result.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, arrays, mathematics, variables and tagged , , , , , , , , , , , , . Bookmark the permalink.