Seeding the .NET random number generator

Occasionally I find myself generating random numbers/strings in C#. An example came up today where a SAML request token needed a unique ID consisting of 41 lowercase alphabet characters, which I generated using the Random class.

The constructor for this class has two overloads:

Random()
Random(int seed)

Apparently, computers don’t actually generate true random numbers but pseudo-random numbers as they are generated following a pattern. The starting point for the pattern is determined by a “seed”. The parameterless constructor uses a time-dependent seed, while the second constructor allows a user-defined seed. Most of the applications that I write involving random numbers use only one instance of the Random class, so I tend to use the following pattern when I instantiate it:

using System;

namespace RandomNumbers
{
    public static class Program
    {
        public static void Main()
        {
            Random random;
            unchecked
            {
                random = new Random((int)DateTime.Now.Ticks);
            }

            Console.WriteLine("Roll: {0}", random.Next(1, 7));
            Console.ReadLine();
        }
    }
}

The unchecked keyword ensures that we don’t get an overflow when we try and squeeze a 64-bit value into a 32-bit variable.