This documentation is archived and is not being maintained.

Random.NextBytes Method

Fills the elements of a specified array of bytes with random numbers.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public virtual void NextBytes (
	byte[] buffer
)
public void NextBytes (
	byte[] buffer
)
public function NextBytes (
	buffer : byte[]
)
Not applicable.

Parameters

buffer

An array of bytes to contain random numbers.

Exception typeCondition

ArgumentNullException

buffer is a null reference (Nothing in Visual Basic).

Each element of the array of bytes is set to a random number greater than or equal to zero, and less than or equal to MaxValue.

To generate a cryptographically secured random number suitable for creating a random password, for example, use a method such as RNGCryptoServiceProvider.GetBytes.

Notes to Inheritors: Starting with the .NET Framework version 2.0, if you derive a class from Random and override the Sample method, the distribution provided by the derived class implementation of the Sample method is not used in calls to the base class implementation of the NextBytes method. Instead, the uniform distribution returned by the base Random class is used. This behavior improves the overall performance of the Random class. To modify this behavior to call the Sample method in the derived class, you must also override the NextBytes method.

The following code example demonstrates how to use the NextBytes method to fill an array of bytes with random byte values.

Random rnd = new Random();
Byte[] b = new Byte[10];
rnd.NextBytes(b);
Console.WriteLine("The Random bytes are: ");
for (int i = 0; i < 10; i++) {
    Console.Write(i);  
    Console.Write(":");
    Console.WriteLine(b[i]);
}

Random rnd = new Random();
ubyte b[] = new ubyte[10];
rnd.NextBytes(b);
Console.WriteLine("The Random bytes are: ");
for (int i = 0; i < 10; i++) {
    Console.Write(i);
    Console.Write(":");
    Console.WriteLine(b[i]);
}

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0
Show: