Share via


Random.NextBytes Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

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

Syntax

'Declaration
Public Overridable Sub NextBytes ( _
    buffer As Byte() _
)
public virtual void NextBytes(
    byte[] buffer
)

Parameters

  • buffer
    Type: array<System.Byte[]
    An array of bytes to contain random numbers.

Exceptions

Exception Condition
ArgumentNullException

buffer is nulla 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.

Notes to Inheritors

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.

Examples

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

Dim rnd As New Random()
Dim b(10) As Byte
rnd.NextBytes(b)
outputBlock.Text += "The Random bytes are: " + vbCrLf
Dim i As Integer
For i = 0 To 9
   outputBlock.Text += i
   outputBlock.Text += ":"
   outputBlock.Text += b(i) + vbCrLf
Next i
Random rnd = new Random();
Byte[] b = new Byte[10];
rnd.NextBytes(b);
outputBlock.Text += "The Random bytes are: " + "\n";
for (int i = 0; i < 10; i++)
{
   outputBlock.Text += i;
   outputBlock.Text += ":";
   outputBlock.Text += b[i] + "\n";
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

See Also

Reference