Edit

Share via


Random.NextBytes Method

Definition

Overloads

NextBytes(Span<Byte>)

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

NextBytes(Byte[])

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

NextBytes(Span<Byte>)

Source:
Random.cs
Source:
Random.cs
Source:
Random.cs

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

public virtual void NextBytes(Span<byte> buffer);

Parameters

buffer
Span<Byte>

The array to be filled with random numbers.

Remarks

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

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Standard 2.1

NextBytes(Byte[])

Source:
Random.cs
Source:
Random.cs
Source:
Random.cs

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

public virtual void NextBytes(byte[] buffer);

Parameters

buffer
Byte[]

The array to be filled with random numbers.

Exceptions

buffer is null.

Examples

The following 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 <= 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

Remarks

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(Byte[]) 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(Byte[]) method.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0