Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi

 

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.

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

  • Leaders
Posted

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.

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...