Random Class [C# .NET 2.0]

anjanesh

Newcomer
Joined
Jun 11, 2005
Messages
4
Location
Mumbai, India
Hi

Code:
Console.WriteLine(new Random().Next(50));
Console.WriteLine(new Random().Next(50));
Console.WriteLine(new Random().Next(50));
always returns the same value while it doesnt when using it as an object.
Code:
Random r = new Random();
Console.WriteLine(nr.Next(50));
Console.WriteLine(nr.Next(50));
Console.WriteLine(nr.Next(50));

Is there some seed to take care of in #1 ?

C# .NET 2.0

Thanks
 
In both cases you are using it as an object. The difference is that in the first case you are creating a new object three times and in the second case you are re-using the same object three times.

What is happening is this: when you use the default constructor for Random, it uses the time as a seed (this way the seed is essentially random). When you run your first code listing the code is executing faster than the computer's clock updates so you are getting the first number from the same list of random numbers three times. With the second code listing, you are getting the first three numbers from the list of random numbers once.

In fact, if you ran the second code listing immediately after the first, you would see that the first number from the second code listing would match all of the numbers from the first listing.
 
Back
Top