Iris Classon
Iris Classon - In Love with Code

Stupid Question 49: Why does 2 x Random not give unique numbers when inside the same method block? (C#)

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

If not used correctly random wont be so random ;)

I’ve always wondered this, as I noticed by accident when I was putting together a small programming demo for non-programmers. It was an magic eight-ball. I found out how to solve the issue, basically I used just one instance and moved it outside the method block but I never actually bothered looking it up as I don’t really use Random a lot. The answer was surprising but made sense:

From MSDN:

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers. You can also work around it by modifying the seed value returned by the system clock and then explicitly providing this new seed value to the Random(Int32) constructor

So basically the Random Object is based on the system clock, and when created and called in quick succession (like 2 + in a method, or even more fun - create it in a loop!) they will likely have the same values. Go figure. I really should look up definitions more often :D Sometimes a bit of reading beats TAED - Trial And Error Development ;)

Comments

Leave a comment below, or by email.
Patrik Löwendahl
9/22/2012 11:58:06 AM
You've probably already found a true random generator. But this discussion is a good one on StackOverflow:

http://stackoverflow.com/questions/668361/fastest-implementation-of-a-true-random-number-generator-in-c-sharp 
Robert Friberg
9/22/2012 1:10:40 PM
A long time ago I generated random one time passwords for multiple users. They all got the same password. Not so secure :) 
James Curran
9/24/2012 7:11:47 AM
Random() is default-seeded with the time in milliseconds, which means you can do quite a bit between two instaniations of Random and still get the same seed.

I was once confronted with this problem.  An object was created & destroyed quite frequently (once for each page served on my website), and in between it used a random number was used.  Creating a new instance of Random for each object caused duplicate seeds, but there was no good place to store a static instance.

Then I recalled that the website used a IOC container.  I just had to make the object dependent on a Random object and then put one in the container. 


Last modified on 2012-09-20

comments powered by Disqus