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 :
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;
}