Click here to Skip to main content
15,867,780 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Can anyone tell me how to generate random numbers so that on every execution it should not generate identical numbers or same numbers.
Posted

Random numbers are started from a seed value: normally the system clock. So it shouldn't matter what you do as long as you don't start the random number generator at the same time!

In C#, it's pretty easy: a class level (possibly even static) instance of the Random class:
C#
private Random rand = new Random();

Then use it to generate your numbers when you want:
C#
for (int i = 0; i < 100; i++)
   {
   int r = rand.Next();
   Console.WriteLine(r);
   }
Should prove the sequence is different for each execution of your code.

If you want a single unique number for each execution, then Id suggest using a Guid instead:
C#
Guid id = Guid.NewGuid();
as these are very, very unlikely to be duplicated.
 
Share this answer
 
Just use the Random class in .NET
make sure you use a different "seed" on each session.

http://msdn.microsoft.com/en-us/library/ctssatww(v=vs.110).aspx[^]

using the same "seed" will cause the Random generator class to create the same sequence again.
 
Share this answer
 

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