How can I generate a random 8 character alphanumeric string in C#?
Just some performance comparisons of the various answers in this thread:
// what's available
public static string possibleChars = "abcdefghijklmnopqrstuvwxyz";
// optimized (?) what's available
public static char[] possibleCharsArray = possibleChars.ToCharArray();
// optimized (precalculated) count
public static int possibleCharsAvailable = possibleChars.Length;
// shared randomization thingy
public static Random random = new Random();
// http://stackoverflow.com/a/1344242/1037948
public string LinqIsTheNewBlack(int num) {
return new string(
Enumerable.Repeat(possibleCharsArray, num)
.Select(s => s[random.Next(s.Length)])
.ToArray());
}
// http://stackoverflow.com/a/1344258/1037948
public string ForLoop(int num) {
var result = new char[num];
while(num-- > 0) {
result[num] = possibleCharsArray[random.Next(possibleCharsAvailable)];
}
return new string(result);
}
public string ForLoopNonOptimized(int num) {
var result = new char[num];
while(num-- > 0) {
result[num] = possibleChars[random.Next(possibleChars.Length)];
}
return new string(result);
}
public string Repeat(int num) {
return new string(new char[num].Select(o => possibleCharsArray[random.Next(possibleCharsAvailable)]).ToArray());
}
// http://stackoverflow.com/a/1518495/1037948
public string GenerateRandomString(int num) {
var rBytes = new byte[num];
random.NextBytes(rBytes);
var rName = new char[num];
while(num-- > 0)
rName[num] = possibleCharsArray[rBytes[num] % possibleCharsAvailable];
return new string(rName);
}
//SecureFastRandom - or SolidSwiftRandom
static string GenerateRandomString(int Length) //Configurable output string length
{
byte[] rBytes = new byte[Length];
char[] rName = new char[Length];
SolidSwiftRandom.GetNextBytesWithMax(rBytes, biasZone);
for (var i = 0; i < Length; i++)
{
rName[i] = charSet[rBytes[i] % charSet.Length];
}
return new string(rName);
}
Tested in LinqPad. For string size of 10, generates:
- from Linq = chdgmevhcy [10]
- from Loop = gtnoaryhxr [10]
- from Select = rsndbztyby [10]
- from GenerateRandomString = owyefjjakj [10]
- from SecureFastRandom = VzougLYHYP [10]
- from SecureFastRandom-NoCache = oVQXNGmO1S [10]
And the performance numbers tend to vary slightly, very occasionally NonOptimized
is actually faster, and sometimes ForLoop
and GenerateRandomString
switch who's in the lead.
- LinqIsTheNewBlack (10000x) = 96762 ticks elapsed (9.6762 ms)
- ForLoop (10000x) = 28970 ticks elapsed (2.897 ms)
- ForLoopNonOptimized (10000x) = 33336 ticks elapsed (3.3336 ms)
- Repeat (10000x) = 78547 ticks elapsed (7.8547 ms)
- GenerateRandomString (10000x) = 27416 ticks elapsed (2.7416 ms)
- SecureFastRandom (10000x) = 13176 ticks elapsed (5ms) lowest [Different machine]
- SecureFastRandom-NoCache (10000x) = 39541 ticks elapsed (17ms) lowest [Different machine]