4

I found this initialization of a Random instance:

var random = new Random(unchecked(Environment.TickCount * 31));

Why not simply use new Random()?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 2
    `Random` has some statistical problems with related tick counts. I think the 31 is supposed to fix that. This code is broken in any case because it relies on ticks. A better way, not the best, is `new Random(NewGuid().GetHashCode())`. – usr Jul 21 '16 at 14:43
  • 4
    It's an utterly useless bit of code. `Random()` already initializes itself based on the `Environment.TickCount`, and C# is unchecked by default. I really wonder what adding the `* 31` does though. – CodeCaster Jul 21 '16 at 14:43

1 Answers1

7

The keyword unchecked prevents an exception from being thrown when the calculation Environment.TickCount * 31 integer overflows.

The resulting calculation is essentially a random integer (it throws away a bunch of high-order bits), which is used to seed the random number generator.

Note that the Reference Source for Random has this code as its parameterless constructor:

public Random() 
    : this(Environment.TickCount) {
  }
mkl
  • 90,588
  • 15
  • 125
  • 265
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • Why is 31? Such "magic number"? Because I saw it in a lot of places. https://github.com/natfoth/LunaSkypeBot/blob/master/LunaSkypeBot/Utillities/Extensions.cs https://stackoverflow.com/questions/273313/randomize-a-listt https://github.com/AdaptiveConsulting/ReactiveTrader/blob/master/src/Adaptive.ReactiveTrader.Shared/Extensions/ArrayExtensions.cs – Selikhov Evgeny Jul 21 '16 at 15:09
  • I don't know. It might be an error. The [Lehmer Random Number Generator](https://en.wikipedia.org/wiki/Lehmer_random_number_generator) uses 2³¹ as a large Mersenne Prime; maybe that's where it came from. – Robert Harvey Jul 21 '16 at 16:01
  • 31 == 2^5 - 1 == 11111 (binary). Multiplying with such a number is meant to spread differences: Even if two numbers differ in only one bit, those two numbers each multiplied with 31 will most likely differ in multiple bits. For a proper seeding implementation of a `random` functionality this shouldn't be necessary, though. – mkl Aug 05 '16 at 07:27