C# Random

Random

With Random,
a class,
we generate pseudo-random numbers. A typical "random" number generator cannot return a truly random number. It instead returns sufficiently random (random-appearing) numbers.

Int

Example

First, Random is a class in the base class library. It is available when we include (or reference) the System namespace. In this program, we use the Random class and its Next method, with two arguments.

Numbers

Argument 1:The first argument to Next() is the inclusive minimum number allowed by the random number generator.

Argument 2:This argument is an exclusive maximum. So it never occurs in the output—all numbers must be lower.

Based on:

.NET 4.5

C# program that uses Random

using System;

class Program
{
    static void Main()
    {
	// ... Create new Random object.
	Random r = new Random();
	// ... Get three random numbers.
	//     Always 5, 6, 7, 8 or 9.
	Console.WriteLine(r.Next(5, 10));
	Console.WriteLine(r.Next(5, 10));
	Console.WriteLine(r.Next(5, 10));
    }
}

Output

5
7
6

Static

Static

Often, using a static Random class instance improves programs. Here, the Random object is stored as a static variable. This ensures that methods that use it will still get good random ints.

Tip:If you used a new Random at the method level as a local, it would not be as good. The time-dependent seed would repeat itself.

C# program that uses static Random

using System;

class Program
{
    static void Main()
    {
	// 1
	// Call method that uses class-level Random
	F();
	// 2
	// Call same method
	// The random number sequence still be random
	F();
    }

    static Random _r = new Random();
    static void F()
    {
	// Use class-level Random so that when this
	// ... method is called many times, it still has
	// ... good Randoms.
	int n = _r.Next();
	// If this declared a local Random, it would
	// ... repeat itself.
	Console.WriteLine(n);
    }
}

Output

1348885989
995018704

Review

Two

Let's look at Microsoft's resources about this Random number generator class. MSDN indicates that by default the Random object uses a seed value. This means that if the time is the same when two Randoms are created, you have a problem.

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to improve randomness is to make the seed value time-dependent.

Random Class: MSDN

MSDN further states how we can use Random for the best performance in our C# programs. We should "create one Random to generate many random numbers over time." This can be done with a local variable or field.

Fields

Field

It is advisable to use the class-level Random field when the methods using it will be called in the same time frame. If you call a method that creates a new Random twice in the same time frame, the Random may have the same result.

State:In object-oriented programming, we think of classes as machines that must store state.

Object-Oriented ProgrammingObject-oriented programming

And:The Random() object has state, which is dependent on time. It is not stateless.

Thus:It is not ideal to create multiple Randoms when you can use only one. With one, we improve randomness and performance.

Max

Cover logo

Continuing on, we review another example of the maxValue parameter on the Next method. When you pass an integer to Random.Next(), you get a result in the range of 0 to maxValue - 1.

Important:You will not get the actual parameter argument you passed, as the top is exclusive.

Another option is to pass the Next() method two parameters, which will have results equal to the minValue to the maxValue - 1. The lower bound is inclusive, but the upper one isn't.

C# program that uses Random with parameter

using System;

class Program
{
    static void Main()
    {
	F();
	F();
	F();
	F();
	F();
	F();
    }

    static Random _r = new Random();
    static void F()
    {
	int n = _r.Next(5);
	// Can return 0, 1, 2, 3, or 4
	Console.WriteLine(n);
    }
}

Output
    (4 is also possible)
2
1
1
0
3
2

Bytes

Byte

You can also call the NextBytes method on the Random type to acquire a random byte array. Each byte has the decimal range of 0 to 255, and you can use the bytes to convert to other types if necessary.

NextBytes:The NextBytes method allows you to get a random value of arbitrary length in one method invocation.

Random Byte Array

Discussion

Logic

When used as shown, the Random class is viable for use in simple games and other non-scientific fields. Do not use it for cryptography. For cryptography in the .NET Framework, use the RNGCryptoServiceProvider class.

RNGCryptoServiceProvider

Note:The RNG stands for random number generator. The name is confusing because of its abbreviation.

C# language

Also:There are more examples of random number usage and other random data generation tactics on this site.

Path.GetRandomFileNameRandom Lowercase LetterRandom ParagraphsRandom StringRandomize Chars in String

Tip:You can use ranges with the Random class. This eliminates the need to use modulo division.

Modulo

Summary

Framework: NET

With Random, often a field or static field gives the best results. We examined a common mistake. Developers should avoid a method-level Random object if the method is called repeatedly in the same time frame.


C#: Number