-1

I want to generate a different random string every time I use the function.

public static Dictionary<string, long> Giftcodes = new Dictionary<string, long>();

private static Random random = new Random();

        public static string GenerateCode()
        {
            string code = "";

            string chars = "abcefhijkmnorsuvwxyzABCDEFHIKMNORSUVWXYZ1234567890";

            if (Giftcodes.Keys == null)
            {
                code = new string(Enumerable.Repeat(chars, 16)
                    .Select(s => s[random.Next(s.Length)]).ToArray());
            }else
            {
                while (!Giftcodes.Keys.Contains(code))
                {
                    code = new string(Enumerable.Repeat(chars, 16)
                        .Select(s => s[random.Next(s.Length)]).ToArray());
                }
            }

            return code;
        }

I did a little bit of researches but I found nothing.

1 Answers1

1

while (!Giftcodes.Keys.Contains(code)) looks very suspicious, basically it does the opposite - it will generate a code until it is present in the dictionary, try changing it to:

do
{
    code = ....
} 
while (Giftcodes.ContainsKey(code));

// ...

Giftcodes.Add(code, 0); // do not forget to add the code
return code;

Also:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132