Skip to content

Instantly share code, notes, and snippets.

@RonenNess
Created December 19, 2021 22:33
Show Gist options
  • Save RonenNess/55d6a1bff7e7037372884101111c550c to your computer and use it in GitHub Desktop.
Save RonenNess/55d6a1bff7e7037372884101111c550c to your computer and use it in GitHub Desktop.
C# random string generator.
// possible characters for the random strings generation
static string _charsForRandomness = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
/// <summary>
/// Generate a random string at a given length.
/// </summary>
public static string GenerateRandomString(int length = 8)
{
// generate random characters
var stringChars = new char[length];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = _charsForRandomness[random.Next(_charsForRandomness.Length)];
}
// turn to string and return
var randomString = new String(stringChars);
return randomString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment