TheDeveloperBlog.com


C# Random Byte Array

Random byte array. A random byte array helps in low-level methods. Each byte in the array is assigned to a random number in range for the type. The NextBytes method on the Random type enables you to get random values of arbitrary length.


Example. This program shows the NextBytes method on the Random type and uses it to acquire a random array of bytes. You can use this method to get a large amount of random data, which you can use for certain simulation-oriented programming tasks.

Tip: While an integer is only four bytes, you can use NextBytes to get much more random data at once.

C# program that uses NextBytes method

using System;

class Program
{
    static void Main()
    {
	// Put random bytes into this array.
	byte[] array = new byte[8];
	// Use Random class and NextBytes method.
	// ... Display the bytes with following method.
	Random random = new Random();
	random.NextBytes(array);
	Display(array);
	random.NextBytes(array);
	Display(array);
    }

    static void Display(byte[] array)
    {
	// Loop through and display bytes in array.
	foreach (byte value in array)
	{
	    Console.Write(value);
	    Console.Write(' ');
	}
	Console.WriteLine();
    }
}

Output

177 209 137 61 204 127 103 88
167 246 80 251 252 204 35 239

We see the Random class and its instance method NextBytes. What NextBytes does is receive the argument byte array, and fills each of the elements in the byte array with a random byte value. Byte values are between 0 and 255.

Tip: You do not need to specify the length of the array. That information is stored inside the array object data itself.

Byte TypeArray Length Property

The program also defines the Display static method. This loops through the byte array parameter and displays each element to the screen on a single line. Often, using an array write method is convenient.


Discussion. The Random class encapsulates methods for acquiring random numbers, which are actually pseudo-random numbers. To use the Random type, you must instantiate it with the constructor.

Then: On the identifier of the Random variable, you can call instance methods to get random data.

Random Number

Summary. We used the NextBytes method on the Random type. This enables you to quickly get a random byte array. Bytes are the smallest addressable memory unit in programming. They can be used to represent any data.

Also: We noted the byte type, the byte array type, and the Random type which generates random numbers.