How do I seed a random class to avoid getting duplicate random values

leora picture leora · Nov 23, 2009 · Viewed 179.3k times · Source

I have the following code inside a static method in a static class:

Random r = new Random();
int randomNumber = r.Next(1,100);

I have this inside a loop and I keep getting the same randomNumber!

Any suggestions here?

Answer

joppiesaus picture joppiesaus · Aug 16, 2013

A good seed generation for me is:

Random rand = new Random(Guid.NewGuid().GetHashCode());

It is very random. The seed is always different because the seed is also random generated.