January 22, 2016

Random Extension

An extension to the Random class to help convert the random number generator class to generate more than just integers. It is very simple to use, pass your array of random choices as parameters to the method.
Hint: Make your Random instance static so that the choice of random values is not continually reset back to the start.
private static Random random = new Random();
...
/// <summary>
/// An extension to the Random class to help convert the random generator to 
/// generate more than just integers. It is very simple to use, pass your 
/// array of random choices as parameters to the method.
/// </summary>
/// <example>
/// For example, say you want something chosen at random from the following 
/// set of football teams:
/// "Liverpool", "Southampton", "Manchester United", "Barcelona"
/// then use the following line: 
/// string randomTeam = random.NextFromSet<T>("Liverpool", 
///                      "Southampton", "Manchester United", "Barcelona");
/// </example>
public static class RandomExtensions
{
 public static T NextFromSet<T>(this Random random, params T[] set)
 {
  return set[random.Next(0, set.Length)];
 }
}

...
string randomTeam = random.NextFromSet<string>("Liverpool", "Southampton", 
      "Manchester United", "Barcelona");

No comments: