C# Random Number Generation

C# Random Number Generation

Random Numbers are a crucial part of computer programming. Random numbers are heavily used in video game programming, statistics, and advanced computing. One thing to take note of is that random numbers that are generated from a computer are not totally random. The random number algorithm depends on the system clock and because of this fact computer random numbers just appear random. Computers are able to produce numbers that are random enough so the human mind can't tell the difference.

C# makes generating random numbers very easy. First we must create a random number object and once the object has been created we can call the Next method to produce random numbers -- like this:

Random RandomNumber = new Random();
int x = RandomNumber.Next();

The Next method without any parameters will produce a random number from 0 to 2,147,483,647. If Next is called again it will generate another random number.
C# Random Number Example

using System;

class Program
{
static void Main(string[] args)
{
Random RandomNumber = new Random();
int x = RandomNumber.Next();
Console.WriteLine(x);
Console.Read();
}
}

Output

562711


if you run this program a few times you will notice that the numbers really do appear random. Just remember that they are random enough to satisfy any program situation.

You can also produce random number up to a certain number for example, you can get a number from 0 to 10:


int x = RandomNumber.Next(10);

You may have a need to produce random number a certain range. To do this you will need to give the Next method some parameters

int x = RandomNumber.Next(6, 10);

This command returns random number between 6 and (10 - 1). The Next method is overloaded 3 times. The third overloaded method is the one above. It takes 2 parameters the min and max.

For those of you that have some knowledge or skill in C++ you may wonder why the C# does not need to be seeded. C# random class is seeded by the system clock in its default constructor, so seeding is not required to produce random numbers in C#.

C# has the ability to produce double random numbher too. The Random class has the NextDouble method to produce double numbers. It will generate double number from 0.0 to 1.0. We will go over how to produce random number in a range using the NextDouble method. In the example below we will create random number from 1.0 to 10.0.


using System;

class Program
{
static void Main(string[] args)
{
Random RandomNumber = new Random();
double x = 1 + RandomNumber.NextDouble() * 9;

Console.WriteLine(x);

Console.Read();
}
}


The code above will produce random numbers from 1.0 to 10.0