1

I wrote below class to gereate a unique 6-digit Random code in database:

public class RndCode
{
    public static string Generate(int ID, int Length = 5)
    {
        string allowedChars = "0123456789";
        char[] chars = new char[Length];
        string code = "";
        Random rd = new Random();

        for (int i = 0; i < Length; i++)
        {
           chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
        }

        string VCode = new string(chars);
        using (DataBaseContext db = new DataBaseContext())
        {
            if (!db.Members.Any(o => o.ID == ID && o.Code == VCode))
            {
                code = VCode;
            }
            else
            {
                Generate(ID, Length);
            }
        }
        return code;
     }
 }

and use it in my controller:

int id = 250;
List<string> AllCodes = new List<string>();
for (int i = 0; i < 20 ; i++)
{
     var RandomCode = Service.RndCode.Generate(id, 6);

     AllCodes.Add(RandomCode);
}

but AllCodes contains more repetitious numbers. why?

What is wrong?

Farzaneh Talebi
  • 835
  • 4
  • 22
  • 47
  • Your recursive call to yourself is also broken because you don't do anything with the result of the recursive call, instead returning `code` which will still just be `""`, if you're lucky and don't cause a stack overflow. And you're only checking codes in the DB - you're not checking codes *you're just generated yourself* in a previous iteration. – Damien_The_Unbeliever Jan 21 '19 at 07:57
  • How to fix this objection? – Farzaneh Talebi Jan 21 '19 at 08:20

0 Answers0