generate a random string in csharp

To generate a random string in C#, you can use the Random class to generate a sequence of random numbers and convert them to characters. Here is a method that generates a random string of a specified length:

main.cs
public static string RandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var random = new Random();
    var result = new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
    return result;
}
309 chars
9 lines

In this example, the chars string contains all the possible characters that can appear in the random string. The method then uses this string and the Random.Next method to select random characters from it and build a string of the specified length.

gistlibby LogSnag