This documentation is archived and is not being maintained.

Random.NextBytes Method

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

[Visual Basic]
Public Overridable Sub NextBytes( _
   ByVal buffer() As Byte _
)
[C#]
public virtual void NextBytes(
 byte[] buffer
);
[C++]
public: virtual void NextBytes(
 unsigned char buffer __gc[]
);
[JScript]
public function NextBytes(
   buffer : Byte[]
);

Parameters

buffer
An array of bytes to contain random numbers.

Exceptions

Exception Type Condition
ArgumentNullException buffer is a null reference (Nothing in Visual Basic).

Remarks

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.

Example

[Visual Basic] 
Dim rnd As New Random()
Dim b(10) As Byte
rnd.NextBytes(b)
Console.WriteLine("The Random bytes are: ")
Dim i As Integer
For i = 0 To 9
    Console.Write(i)
    Console.Write(":")
    Console.WriteLine(b(i))
Next i

[C#] 
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]);
}

[C++] 
Random *rnd = new Random();
unsigned char b __gc[] = new  unsigned char __gc[10];
rnd->NextBytes(b);
Console::WriteLine(S"The Random bytes are: ");
for (int i = 0; i < 10; i++) {
   Console::Write(i);  
   Console::Write(S":");
   Console::WriteLine(b[i]);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

Random Class | Random Members | System Namespace | Byte

Show: