C# 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 appear very random.

Example

First, the Random type is a class in the base class library. It is available in programs that include the System namespace. In this program, we see an example of using the Random class.

Next:The Random object is stored as a static variable. This ensures that methods that use it will still get good random ints.

Int

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.

Program that uses static Random: 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

Review

This section provides information

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

Object-oriented programming

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.

In object-oriented programming, 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

Note

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.

Important: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

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.

Discussion

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.

Byte type

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.

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

Random Byte Array

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

Path.GetRandomFileNameRandom Lowercase LetterRandom Paragraphs and SentencesRandom StringRandomize Chars in String

Summary

Framework: NET

We used the Random class in the .NET Framework in a way that gets the best results. One common mistake developers make is using a method-level Random object in a method that is called in the same time frame.

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

Modulo Operator

C#: Number