[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Select random objects from an array in C#

[Select random objects from an array in C#]

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 the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.