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[]
)

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.

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 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 .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show: