Possible Duplicate:
Random number generator only generating one random number
I have a method in my work which generates a sentence by randomly choosing between a set of words as follows:
private string generateTest(string test)
{
test = test.ToLower();
string sentence = "";
for (int c = 0; c < 30; c++)
{
Random r = new Random();
int len = r.Next(3, 7);
string word = "";
for (int i = 0; i < len; i++)
{
word += test[r.Next(0, test.Length)];
}
sentence += word + ' ';
}
return sentence;
}
However, the problem is that after the first 6 words are generated randomly, all subsequent generations are exactly the same thing. e.g.
aqaaaz, qqzaq, aqqza, azqq, aazzq, aqqa, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq....
Then even when I restart the program, the same thing applies. I am thinking this is the .NET Runtime doing some automatic optimization. Can anyone explain better? How do I get around this problem?