Click here to Skip to main content
15,895,865 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Random ranNum = new Random();

string colorName= "pic" + arrayColors[ranNum.Next(0, 6)];

I tried this code in ASP.NET but in a for loop but the random number seems to stay the same for each loop. How can I make it different for each loop?
Posted
Comments
Jibesh 12-Feb-13 3:03am    
where you created the ranNum instance inside loop? try to define it outside loop and use the ranNum.Next inside the loop to get the random number
GreenKhan 12-Feb-13 3:05am    
Read my mind, I just tried that as you said. And yes you are correct it worked! :) Thanks!

The problem is generally that you are creating a new instance of the Random class each time - when you do this, it is initialised from the system clock, and if you create them close together you will get the same "random" sequence each time.
To avoid that, declare your Random object at class level:
C#
private Random ranNum = new Random();
and use the same instance each time you want a new random number.
 
Share this answer
 
Comments
Maciej Los 12-Feb-13 3:25am    
Short and to the point! +5!
Random takes a seed value which will mix up the start point:
C#
Random r = = new Random(new System.DateTime().Millisecond);
 
Share this answer
 
Comments
Thomas Daniels 12-Feb-13 3:09am    
Hi,

I don't think this will make any difference. According to my decompiler, if you create an instance of the Random class, then the seed value is Environment.TickCount. So the start point is already mixed up.
As Jibesh said, put
C#
Random ranNum = new Random();

outside the for loop

and this inside
C#
string colorName= "pic" + arrayColors[ranNum.Next(0, 6)];

--------------------------------
CODE
------------------------------------
C#
Random ranNum = new Random();

for (i = 0;i<10;i++){

string colorName= "pic" + arrayColors[ranNum.Next(0, 6)];
}


[Edit]Code blocks added[/Edit]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900