C# Random Byte Array

Byte type

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 in the C# language and .NET Framework enables you to get random values of arbitrary length—not just four-byte integers.

Example

Note

This simple example program shows the NextBytes method on the Random type and how you can use it to acquire a random array of bytes. Essentially, you can use this method to get a very large amount of random data, which you can use for certain simulation-oriented programming tasks. While an integer is only four bytes, you can use NextBytes to get much more random data at once.

This C# example program shows how to create random byte arrays with the Random type.

Program that uses NextBytes method [C#]

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
Random type

NextBytes. This program demonstrates the use of 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. You do not need to specify the length of the array, as that information is stored inside the array object data itself.

Byte Type Array Length Property

Overview. The program also defines the Display static method, which simply loops through the byte[] array parameter and displays each element to the screen on a single line. Often when debugging or implementing simple console programs, using an array write method is convenient.

Random number generators

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

The C# programming language

We looked at the NextBytes method on the Random type, which enables you to quickly get a random array of bytes in the C# language. Bytes are the smallest addressable memory unit in programming, and can be used to represent any data that can be stored in memory or on disk. We noted the byte type, the byte[] array type, and the Random type which generates random numbers.

Array Types
.NET