create a password with numbers in csharp

Here's a code snippet that creates a random password with numbers in C#:

main.cs
public static string GeneratePassword(int length)
{
    const string validChars = "0123456789";
    var rng = new Random();
    var chars = new char[length];
    
    for (int i = 0; i < length; i++)
    {
        chars[i] = validChars[rng.Next(0, validChars.Length)];
    }
    
    return new string(chars);
}
312 chars
14 lines

In this implementation, we define a string of valid characters that can be included in the password (in this case, just numbers 0-9). We then create a new instance of the Random class, and use this to generate a random number between 0 and the length of validChars. We repeat this process, adding a randomly selected character from validChars to the chars array for each iteration of the loop. Finally, we return a new string created from the resulting chars array.

To use this method, simply call GeneratePassword() and pass in the desired length of the password as an integer parameter.

gistlibby LogSnag