snippetcsharpCritical
How can I generate random alphanumeric strings?
Viewed 0 times
alphanumerichowrandomstringsgeneratecan
Problem
How can I generate a random 8 character alphanumeric string in C#?
Solution
I heard LINQ is the new black, so here's my attempt using LINQ:
(Note: The use of the
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}(Note: The use of the
Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)Code Snippets
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}Context
Stack Overflow Q#1344221, score: 2214
Revisions (0)
No revisions yet.