Generate Random String 1

Generate Random String

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());
}

Here is what the above code is Doing:
1. We’re creating a new Random object.
2. We’re creating a new string that contains all the characters we want to use.
3. We’re using LINQ to create a new string that is the length we want.
4. We’re using LINQ to select a random character from our character string for each character in our output string.
5. We’re returning the output string.

Similar Posts