Below is my code for generating a random string of random length. I am using it in integration tests. Currently I have almost 2000 tests running each time a commit is made to master and a few of those tests are using this class.
I would like to make sure the code is optimized so that the tests complete as quickly as possible.
public class Strings
{
private static readonly Random Random = new Random();
private static int RandomChar => Random.Next(char.MinValue, char.MaxValue);
public static string GenerateRandomStringOfSetLength(int length)
{
return GenerateRandomString(length);
}
private static string GenerateRandomString(int length)
{
var stringBuilder = new StringBuilder();
while (stringBuilder.Length - 1 <= length)
{
var character = Convert.ToChar(RandomChar);
if (!char.IsControl(character))
{
stringBuilder.Append(character);
}
}
return stringBuilder.ToString();
}
}