Hello all,
I am confused by this issue…
Below is some quick code I threw together to test some random number generation and output. The method in the genNum class simply create a string of 9 unique random numbers from 1 to 9 and returns it.
On my button click event it creates 3 separate instances of the genNum class (g1, g2, g3) and then outputs the string to the corresponding textBox (i.e. g1 => textBox1)
Now if I simply run this code without breakpoints, when I click the button it fills the three textbox controls with the same value. I have attached an image of this occurring.
However, if I run it with a breakpoint on, let’s say set on the button click, and step through all the code it runs just fine meaning that in the end it displays 3 separate strings/
This is pretty consistent for me. Every once in awhile (1 out of 1000 times) it will display a separate value in one of the textboxes, usually the last one if I run it without breakpoints. It is 100% fine if I run it with breakpoints.
Here is the code…
namespace TESTingRndGen
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
genNum g1 = new genNum();
genNum g2 = new genNum();
genNum g3 = new genNum();
textBox1.Text = g1.GenerateStringofNumbers();
textBox2.Text = g2.GenerateStringofNumbers();
textBox3.Text = g3.GenerateStringofNumbers();
}
}
class genNum
{
public string GenerateStringofNumbers()
{
Random rnd = new Random();
string result = "";
int _randomNumHolder;
// Generate 9 random numbers
for(int x = 0; x < 9; x++)
{
_randomNumHolder = rnd.Next(1, 10);
if(x == 0)
result = _randomNumHolder.ToString();
else
{
if(result.Contains(_randomNumHolder.ToString()))
{
--x;
}
else
{
result += _randomNumHolder.ToString();
}
}
}
return result;
}
}
}
Any insight into this would be greatly appreciated!