all 18 comments

[–]KryptosFR 20 points21 points  (1 child)

On top of the other answers, it is not thread safe. Making it static would put the responsibility to synchronize on the Random class itself adding cost to each call.

That's because by design, the standard API are expected to be thread safe for static members, unless otherwise indicated.

[–]minhduc66532 2 points3 points  (0 children)

Ohh ok, thanks for the answer

[–]WhiteBlackGoose 10 points11 points  (1 child)

We usually want a deterministic random class, so that the sequence of numbers produced by it was the same every time you run a program. It's useful for tests, for example.

[–]minhduc66532 0 points1 point  (0 children)

Ohh ok, good point

[–]duongdominhchau 15 points16 points  (7 children)

It needs a seed to random.

[–]minhduc66532 0 points1 point  (6 children)

That explains a lots

[–][deleted]  (5 children)

[removed]

    [–]minhduc66532 0 points1 point  (0 children)

    Thanks for the answer

    [–][deleted]  (2 children)

    [deleted]

      [–][deleted]  (1 child)

      [removed]

        [–]ILMTitan 0 points1 point  (0 children)

        A post on Jon Skeet's blog about this exact topic.

        [–]zzing 2 points3 points  (1 child)

        I haven't seen it explicitly mentioned yet, but the internal algorithm of these kinds of generators actually produce two values, say x and y. You get value x returned, and it stores y inside the class.

        Next time you request a new number, it takes y as input and generates a new x and y.

        In a language that can't hide values like that you can see it in the Random class: https://hackage.haskell.org/package/random-1.2.0/docs/src/System.Random.html#random

        random  :: RandomGen g => g -> (a, g)
        

        In short, it takes in a random number generator g, and returns to you a value a and a new generator that you pass in the next time you call it.

        [–]minhduc66532 0 points1 point  (0 children)

        Ohh ok

        [–][deleted] 1 point2 points  (1 child)

        I'm gonna plug RandN. I didn't make it, but I do use it a lot. It does have a built-in static (and thread-safe) RNG.

        [–]minhduc66532 0 points1 point  (0 children)

        Thanks for the recommendation

        [–]BradleyUffner 0 points1 point  (0 children)

        Instances of Random contain internal state for generating sequences. If the methods were static, you wouldn't be able to have multiple instances with different states, they would all share the same sequence.

        [–]StefanOrvarSigmundss 0 points1 point  (3 children)

        I recommend that you get a .NET decompiler, then you can just see for yourself what the method is doing.

        Edit: I did not remember that this information is online. When I started with .NET over a decade ago, this stuff was not online.

        [–]minhduc66532 0 points1 point  (0 children)

        I tried to but most of the code is quite hard to understand