For testing purpose, I need to generate some random string (contains only letters without any other special characters) with customized length. So I extends the C# built-in Random class like this:
#region Random's Extension
public static class RandomExtension
{
///
/// Returns a random character between the start and end characters specified
///
///
/// The start of the range that the next random character will be generated from
/// The end of the range that the next random character will be generated from
/// A character whose ASCII code greater than or equal to the start's and less than or equal to the end's
public static char NextChar(this Random rnd, char start = 'a', char end = 'z')
{
int startCode = (int)start;
int endCode = (int)end + 1;
if (startCode <= endCode)
{
int code = rnd.Next(startCode, endCode);
return (char)code;
}
else
{
throw new ArgumentException("The 'start' character can NOT be greater than the 'end' charcater", "start");
}
}
///
/// Returns a random character among a set of specified characters
///
///
/// A set of the characters that the new random character will be generated from
/// A character from the specified character set
public static char NextChar(this Random rnd, char[] candidates)
{
if (candidates.Length > 0)
return candidates[rnd.Next(0, candidates.Length)];
else
throw new ArgumentException("Must specify at least 1 character in the array (char[] candidates).", "candidates");
}
///
/// Returns a random letter character ({'a' - 'z'} + {'A' - 'Z'})
///
///
/// A character of the 26 English letters ignoring case.
public static char NextLetter(this Random rnd)
{
return rnd.NextChar(new char[] { rnd.NextChar('a', 'z'), rnd.NextChar('A', 'Z') });
}
///
/// Returns a random letter string (a string contains only letters, no other special characters) with customized length
///
///
/// The length that the random string will be in
/// A string contains only letters.
public static string NextLetterString(this Random rnd, int length = 10)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
sb.Append(rnd.NextLetter());
}
return sb.ToString();
}
}
#endregion