C#: Why Are My Random Numbers Not Random?

Question

So I have this code, which is supposed to generate a new random number every time it is called:

        public static int GetSomeRandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }

In my program, I’m using the above method to let me select five pumpkin colors at random (just don’t ask why):

        enum PumpkinColor
        {
            Red = 0,
            Green = 1,
            Blue = 2
        }

        static void Main(string[] args)
        {
            // write five random pumpkin colors
            for (int i = 0; i < 5; ++i)
            {
                PumpkinColor color = (PumpkinColor)GetSomeRandomNumber(0, 3);
                Console.WriteLine(color);
            }
        }

However, when I run my program, this is the output:

Blue
Blue
Blue
Blue
Blue

Blimey. Not very random now, is it? What gives?

Short Answer

Don’t use a local Random instance in quick loops. Use a shared instance instead:

        private static Random random = new Random();

        public static int GetSomeRandomNumber(int min, int max)
        {
            return random.Next(min, max);
        }

This new implementation now returns:

Green
Red
Red
Blue
Blue

But why does this happen?
And what care do I need to have with static implementations?

Continue reading “C#: Why Are My Random Numbers Not Random?”

Advertisements