C# Random Number

Number Random

Random type

Random number generators cannot return truly random numbers. They return instead sufficiently random numbers. With the Random type in the .NET Framework, we generate in our C# programs numbers that are appear very random. This satisfies almost all algorithms and requirements that involve random numbers.

These C# examples use the Random class. Random is used as a field.

Example

First, the Random type is a class in the base class library, and is available in programs that include the System namespace. Here we see an example of using the Random class. Please note that the Random object is stored at the class level as a static variable, which means that method that use it will still get good random numbers.

Program that uses static Random instance [C#]

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

Description. As noted in the comment, if you used a new Random() at the method level as a local, it would not be as good because the time-dependent seed would repeat itself.

Review

Note

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. "The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated."

More from MSDN. "One way to improve randomness is to make the seed value time-dependent." This means that if the time is the same when two Randoms are created, you have a problem. The third important fact is that for best performance, you should "create one Random to generate many random numbers over time."

MSDN reference

Fields

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

Object-oriented programming. In OOP, we think of classes as machines that must store state. The Random() object has state, which is dependent on time. It is not ideal to create multiple Randoms when you can use only one.

Example 2

Continuing on, we see an example of using the maxValue parameter on the Random.Next method. When you pass an integer to Random.Next(), you get a result in the range of 0 to maxValue - 1. You will not get the actual parameter argument you passed, as the top is exclusive.

Program that uses Random with parameter [C#]

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

Note: 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.

Notes

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. The RNG stands for random number generator.

RNGCryptoServiceProvider ExampleByte type

Acquiring random byte arrays. 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. The NextBytes method allows you to get a random value of arbitrary length in one method invocation.

Random Byte Array

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

Path.GetRandomFileName Method Random Lowercase Letter Random Paragraphs and Sentences Random String Randomize Chars in String

Summary

.NET Framework information

We saw how you can use the Random class in the .NET Framework and get the best results. One common mistake developers make is use a method-level Random object in a method that is called in the same time frame. You can use ranges with the Random class, which is mainly for convenience so you don't need to do modulo division.

Modulo Operator
.NET