Export (0) Print
Expand All

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
)

Parameters

buffer
Type: System.Byte[]

An array of bytes to contain random numbers.

ExceptionCondition
ArgumentNullException

buffer is null.

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

For example, to generate a cryptographically secured random number suitable for creating a random password, 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 example demonstrates how to use the NextBytes method to fill an array of bytes with random byte values.

using System;

public class Example 
{
    public static void Main() 
    {
        Random rnd = new Random();
        Byte[] b = new Byte[10];
        rnd.NextBytes(b);
        Console.WriteLine("The Random bytes are: ");
        for (int i = 0; i <= b.GetUpperBound(0); i++) 
            Console.WriteLine("{0}: {1}", i, b[i]);  
    }
}
// The example displays output similar to the following: 
//       The Random bytes are: 
//       0: 131 
//       1: 96 
//       2: 226 
//       3: 213 
//       4: 176 
//       5: 208 
//       6: 99 
//       7: 89 
//       8: 226 
//       9: 194

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft