Gewoo Gewoo - 3 months ago 12
C# Question

How does the C# Random class work

I wanted to understand how the C#

Random.next()
worked so I started searching up some things and I red it gets a random seed from the clock like this:
DateTime.Now.Millisecond
. So I thought if you create a lot of Random objects in a row it will spit out the same number, I wanted to check that and created this code snippet.

static void Main(string[] args)
{
Random rn;
while (true)
{
rn = new Random();
Console.WriteLine(DateTime.Now.Millisecond.ToString());
Console.WriteLine(rn.Next(10));
}

}


And when I ran this I got of course a lot of number which where the same, but what I thought was when the
DateTime.Now.Millisecond
is going to change, it also will change the random number, but this is not the case as you can see in this output.

9
127
9
127
9
127
9
127
9
127
9
127
9
127
9
128
9
128
9
128
9
128
9
128
9


So why doesn't the random number changes when the
DateTime.Now.Millisecond
change? Please note I just started learning C# so I am sorry if I made a lot of mistakes.

Answer

According to the source code, the parameterless constructor is defined as:

  public Random() 
    : this(Environment.TickCount) {
  }

Which means that it doesn't use the DateTime.Now.Millisecond as the seed, but rather the Environment.TickCount value.

So if you write your code like this:

Random rn;
while (true)
{
    rn = new Random();
    Console.WriteLine(Environment.TickCount);
    Console.WriteLine(rn.Next(10));
}

It should produce the expected output. Try it!

Comments