Random Numbers C#

Generating random numbers in C# .NET (or VB .NET) is pretty simple. Just use the ‘Random’ class

You can specify the minimum and maximum values that the C# random number will fall between, the example below will create a random number between 1 and 10.

using System;
using System.Text;

namespace RandomGen
{
    class Program
    {
        static void Main(string[] args)
        {

            Random random = new Random();
            int i = random.Next(1, 11);

            Console.WriteLine(i.ToString());
            Console.ReadLine();

        }
    }
}

Using The ‘Seed’ When Creating C# Random Numbers

The C# or VB.NET Random class also allows a ‘seed’ to be passed into the constructor which can be used to increase the ‘randomness’ as the default seed is the system time. If you generate lots of random numbers at the same time using C#, without using a random ‘seed’ you may end up with identical results.

A handy way to create a random seed is to use a GUID and convert part of it to an int

using System;
using System.Text;

namespace RandomGen
{
    class Program
    {
        static void Main(string[] args)
        {
            string seedstr = Guid.NewGuid().ToString().Substring(0, 8);
            int seed = int.Parse(seedstr, System.Globalization.NumberStyles.HexNumber);

            Random random = new Random(seed);
            int i = random.Next(1, 11);

            Console.WriteLine(i.ToString());
            Console.ReadLine();

        }
    }
}