Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to solve System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.' exception while generating random code?

I’m getting System.StackOverflowException: ‘Exception of type ‘System.StackOverflowException’ was thrown.’ while generating random numeric string using Random.

protected void btnOrder_Click(object sender, EventArgs e)
{
    string OrderId = "TEK" + CreateRandomCode(15);
}
public string CreateRandomCode(int codeCount = 15)
{
 string allChar = "0,1,2,3,4,5,6,7,8,9";
 string[] allCharArray = allChar.Split(',');
 string randomCode = "";
 int temp = -1;
 Random rand = new Random();//here I'm getting exception

 for (int i = 0; i < codeCount; i++)
 {
  if (temp != -1)
  {
   rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
  }
  int t = rand.Next(10);
  if (temp != -1 && temp == t)
  {
   return CreateRandomCode(codeCount);
  }
  temp = t;
  randomCode += allCharArray[t];
 }
 return randomCode;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The exception is happening because your code is recursive and has no proper base case (exit condition). There is a maximum recursion depth you can have. If you go over that you get a System.StackOverflowException.

Modify your code to have a proper base case or change it completely. As far as I can tell you just want to generate a string which starts with TEK plus in your case 15 numbers attached to it.

The following creates a string containing 15 random digits:

public string CreateRandomCode(int codeCount = 15)
{
 string allChar = "0,1,2,3,4,5,6,7,8,9";
 string[] allCharArray = allChar.Split(',');
 string randomCode = "";
 Random rand = new Random();
 for (int i = 0; i < codeCount; i++)
 {
  randomCode += allCharArray[rand.Next(0, allCharArray.Length)]; 
 }
 return randomCode;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading