0

I created a Random class object named x within a for loop and called x.next(1,7) which should return a variable between 1 and 6, both object creation and x.next() function is placed inside the for loop which executes 5 times instead of returning random variables it returns same value in each iteration

using System;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            for(int i=1;i<=5;i++)
            {
                Random x = new Random();

                Console.WriteLine( x.Next(1,7));
            }

        }
    }
}

My output is as follows

5
5
5
5
5

When i place the object declaration outside the loop it returns random variables in each iteration

 using System;


        namespace ConsoleApplication1
        {
            class Program
            {

                static void Main(string[] args)
                {
                    Random x = new Random();
                    for(int i=1;i<=5;i++)
                    {


                        Console.WriteLine( x.Next(1,7));

                    }

                }
            }
        }

This time my output is

4
5
9
3
1

and also works when x is declared as static variable of class Program as follows

using System;


    namespace ConsoleApplication1
    {
        class Program
        {
            static Random x = new Random();
            static void Main(string[] args)
            {

                for(int i=1;i<=5;i++)
                {


                    Console.WriteLine( x.Next(1,7));

                }

            }
        }
    }

now output is

4
7
3
7
9

But i want to know why it returned same values when object is declared inside the loop and what happens when object variable is declared as static??

Harish K
  • 31
  • 3
  • I want to know specific what happens when object variable (here x) is declared as static variable of a class ( here Program) – Harish K Jan 31 '14 at 09:51

1 Answers1

4

It happens because the default constructor for Random uses the current system clock time for the seed.

Because the system clock time only updates a few times a second, if you construct a lot of Random objects in a tight loop, they will be created so quickly that the system clock time hasn't changed inbetween, resulting in them using the same seed.

If two Random objects are constructed with the same seed, they will generate the same sequence of random numbers. This is what your are seeing.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • 1
    Very good answer, something I didn't know. Tried the sample code but with a loop of 100,000 and you do start to see some different numbers eventually appear but they are still long sequences of the same number which would still match the explanation above. – Peter Monks Jan 31 '14 at 10:01
  • @Gurukulum: output comes different due to Random class you used in the code which works on the system clock time. – SkoolBoyAtWork Jan 31 '14 at 13:31