0

I'm trying to create a unique code generator and I'm using the solution found here: How can I generate random alphanumeric strings?

When I run the app the console outputs the same string 8 times instead of outputting 8 different codes. However if I slow the app down by adding sleep (20ms) between each write then the code outputs 8 different strings.

class Program
{
    static void Main(string[] args)
    {
        // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
        for (int i = 0; i < 8; i++)
        {
            string code = GetUniqueCode(8);
            Console.WriteLine(code);
        }
        Console.ReadKey();
    }

    private static string GetUniqueCode(int length)
    {
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var stringChars = new char[length];
        var random = new Random();

        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[random.Next(chars.Length)];
        }

        var finalString = new String(stringChars);
        return finalString;
    }
}
Theraot
  • 31,890
  • 5
  • 57
  • 86
MattSavage
  • 778
  • 1
  • 7
  • 17

0 Answers0