anjanesh Posted August 17, 2007 Posted August 17, 2007 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 Quote
Leaders snarfblam Posted August 17, 2007 Leaders Posted August 17, 2007 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. Quote [sIGPIC]e[/sIGPIC]
anjanesh Posted August 18, 2007 Author Posted August 18, 2007 Thanks for explanation marble. Had a feeling it had to so with time seed, just couldnt figure out how. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.