Thursday, February 3, 2011

Random Number Generation - Not Random At All

using System;

namespace MyRandom
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                // Generate random number
                Random random = new Random();
                int myNum = random.Next(0, 10);
                // Write generated random number to console window
                Console.WriteLine("My random number: " + myNum.ToString());
            }
            // Pause running console window
            Console.ReadLine();
        }
    }
}

Did you know that if you declared Random Class within the loop as shown in the code sample above, it will not generate random number at all – in fact it will generate same number as shown in the screenshot below:

RandomNumber

To fix this problem, you need to declare Random Class outside of for loop as follows:

using System;

namespace MyRandom
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            for (int i = 0; i < 10; i++)
            {
                // Generate random number
                int myNum = random.Next(0, 10);
                // Write generated random number to console window
                Console.WriteLine("My random number: " + myNum.ToString());
            }
            // Pause running console window
            Console.ReadLine();
        }
    }
}

No comments: