0

Possible Duplicate:
class System.Random .. why not static?

Following on from "Generated random numbers are always equal", I was wondering;

Why doesn't the Random class expose a static method for Next with an optional minimum and maximum? This might sound like a silly question, but from experience, 9 times out of 10 I want to generate a random number, without having to explicitly specify a seed? Am I missing something obvious, is there a reason for this? Or is there in fact a method that I'm explaining that I'm yet to discover?

Community
  • 1
  • 1
Richard
  • 8,110
  • 3
  • 36
  • 59
  • Already answered - see http://stackoverflow.com/questions/4933823/class-system-random-why-not-static – dash May 15 '12 at 09:58

1 Answers1

6

This might sound like a silly question, but from experience, 9 times out of 10 I want to generate a random number, without having to explicitly specify a seed?

You shouldn't be using a static method for that though. You should be using an instance method on something which does maintain state. If you create a new instance of Random every time you call Next, you'll end up with repeated numbers if you call it several times in quick succession.

You should regard "a source of random numbers" as a dependency like any other, IMO - injectable in order to be testable. Of course, if you're not using dependency injection then this argument may not apply... but then you've got other problems.

You probably want one instance of Random per thread, as Random isn't thread-safe.

See my article on random numbers for more details and code samples.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194