0
Random rand = new Random(10);
Console.WriteLine(rand.Next(100));

These couple of lines of code always gives 95 as the output. And when I make the parameter value of the constructor in the first line "8", then the code always gives 90 as the output. Can anybody point to me why it behaves like this ?

P.S: I'm guessing it's something to do with what the parameter value does to the object of the Random class, but a concrete insight into the behavior would be highly appreciated.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Ron16
  • 445
  • 6
  • 11
  • 4
    If you use the same seed you get the same numbers. If you use the default constructor you get different values because its seeded with the current time. – Tim Schmelter Oct 10 '15 at 01:43

1 Answers1

4

You're creating Random instance with the same seed value. It will return the same results when Next is called and that's by design.

Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers.

from Random Constructor (Int32)

Use parameterless constructor to get instance seeded with time-based value.

The default seed value is derived from the system clock and has finite resolution ...

from Random Constructor ()

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Just let me know if you disagree with the closure. Or I think you'll be able to re-open it. – abatishchev Oct 10 '15 at 02:04
  • It's not a duplicate, at least not of a question you linked. That question is about creating multiple `Random` instances within short period of time (e.g. in a loop). This one is about seeding `Random` with predefined seed. – MarcinJuraszek Oct 10 '15 at 02:07
  • Thanks, Marcin. Yeah, it makes sense now. :) – Ron16 Oct 11 '15 at 01:17