Random.NextBytes() Method in C#

The Random.NextBytes() method in C# is used to fill the elements of a specified byte array with random numbers. Each element in the array receives a random value between 0 and 255 (the range of a byte).

Syntax

Following is the syntax for the NextBytes() method −

public virtual void NextBytes(byte[] buffer);

Parameters

  • buffer − An array of bytes to be filled with random numbers. The array must be initialized before calling this method.

Return Value

This method does not return a value. It modifies the passed byte array directly by filling it with random bytes.

NextBytes() Operation byte[] array [0, 0, 0, 0, 0] NextBytes() filled array [173, 92, 210, 11, 52] Each byte: 0-255 range

Using NextBytes() to Fill a Byte Array

Example

using System;

public class Demo {
   public static void Main() {
      Random r = new Random();
      byte[] arr = new byte[5];
      
      r.NextBytes(arr);
      
      Console.WriteLine("Random bytes in the array:");
      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine("arr[" + i + "] = " + arr[i]);
      }
   }
}

The output of the above code is −

Random bytes in the array:
arr[0] = 173
arr[1] = 92
arr[2] = 210
arr[3] = 11
arr[4] = 52

Using Multiple Random Instances

Example

using System;

public class Demo {
   public static void Main() {
      Random r1 = new Random();
      Random r2 = new Random();
      
      byte[] arr1 = new byte[3];
      byte[] arr2 = new byte[3];
      
      r1.NextBytes(arr1);
      r2.NextBytes(arr2);
      
      Console.WriteLine("First array:");
      foreach (byte b in arr1) {
         Console.WriteLine(b);
      }
      
      Console.WriteLine("\nSecond array:");
      foreach (byte b in arr2) {
         Console.WriteLine(b);
      }
   }
}

The output of the above code is −

First array:
210
92
112

Second array:
52
173
11

Generating Random Bytes for Cryptographic Use

Example

using System;

public class Demo {
   public static void Main() {
      Random r = new Random();
      byte[] buffer = new byte[8];
      
      r.NextBytes(buffer);
      
      Console.WriteLine("8 random bytes:");
      for (int i = 0; i < buffer.Length; i++) {
         Console.Write(buffer[i].ToString("X2") + " ");
      }
      Console.WriteLine();
      
      Console.WriteLine("\nAs decimal values:");
      foreach (byte b in buffer) {
         Console.Write(b + " ");
      }
   }
}

The output of the above code is −

8 random bytes:
D2 5C 70 34 AD 0B 7F 95 

As decimal values:
210 92 112 52 173 11 127 149 

Conclusion

The NextBytes() method provides an efficient way to fill byte arrays with random values ranging from 0 to 255. This method modifies the array in-place and is commonly used for generating random data buffers, initialization vectors, or test data in applications.

Updated on: 2026-03-17T07:04:36+05:30

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements