C#

Random. A number is 5. Then it is 8. Then 2, 10, 0. What is the order? There is no order—the numbers are random, they are ordered randomly.
With the Random class, we generate pseudo-random numbers. A typical "random" number generator cannot return a truly random number.

Instead:A random number generator returns sufficiently random (random-appearing) numbers.

Int

Crypto:For simple tasks, the Random class is good enough. But for complex things, a RNGCryptoServiceProvider is better.


First, Random 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.

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. A static thing only has one instance. A static Random improves programs. Here the Random object is stored as a static variable. 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. 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.

Important: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
Review, continued. MSDN further states how we can use Random for the best performance in our C# programs. Some advice is provided.

One random:We should "create one Random to generate many random numbers over time." This can be done with a local variable or field.


Fields. Suppose a method uses a local Random and creates it on each call. If it is called twice in the same time frame, its random numbers may repeat.

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

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. Here is 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.

Also:Another option is to pass the Next() method two parameters. 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

2
1
1
0
3
2
Bytes. 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.Random: NextBytes

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


RNGCryptoServiceProvider. The Random class is not as random as possible. 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.


Shuffle array. A deck of cards is shuffled. In shuffling an array, we rearrange elements in a random order. I use a tested algorithm.Shuffle Array
Random examples. There are more examples of random number usage and other random data generation tactics on this site. For a random string, try using GetRandomFileName.Random Path: GetRandomFileNameRandom Lowercase LetterRandom ParagraphsRandom StringRandom Chars
Modulo. You can use ranges with the Random class. This eliminates the need to use modulo division. But when doing numeric operations, modulo is still sometimes needed.Modulo
With Random, often a field or static field gives the best results. For complex needs, RNGCryptoServiceProvider may be superior. We examined a common mistake.
A final tip. Developers should avoid a method-level Random object if the method is called repeatedly in the same time frame. Instead, calling the same Random is a safer plan.