Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why initialize a new Random() with unchecked(Environment.TickCount * 31)?

Tags:

c#

random

I found this initialization of a Random instance:

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

Why not simply use new Random()?

like image 983
Selikhov Evgeny Avatar asked Mar 11 '23 15:03

Selikhov Evgeny


1 Answers

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) {
  }
like image 145
Robert Harvey Avatar answered Apr 09 '23 02:04

Robert Harvey