Skip to content

Instantly share code, notes, and snippets.

@RhysC
Created March 19, 2011 15:37
Show Gist options
  • Save RhysC/877543 to your computer and use it in GitHub Desktop.
Save RhysC/877543 to your computer and use it in GitHub Desktop.
Provides random values for simple types
public static class Random
{
private static readonly System.Random rand = new System.Random();
public static int Int(int maxValue = int.MaxValue)
{
return rand.Next(maxValue);
}
public static bool Bool()
{
return rand.Next() % 2 == 0;
}
//Decimal - http://stackoverflow.com/questions/609501/generating-a-random-decimal-in-c/609529#609529
public static decimal Decimal()
{
byte scale = (byte)rand.Next(29);
bool sign = rand.Next(2) == 1;
return new decimal(rand.NextInt32(),
rand.NextInt32(),
rand.NextInt32(),
sign,
scale);
}
private static int NextInt32(this System.Random rng)
{
unchecked
{
int firstBits = rng.Next(0, 1 << 4) << 28;
int lastBits = rng.Next(0, 1 << 28);
return firstBits | lastBits;
}
}
public static string String(int size = 50)
{
var builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rand.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
public static T RandomEnum<T>()
{
T[] values = (T[])Enum.GetValues(typeof(T));
return values[rand.Next(0, values.Length)];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment