C# | Random.NextBytes() Method

The NextBytes(Byte[]) method of the System.Random class in C# is used to fill the elements of a specified array of bytes with random numbers. This method takes a byte array as a parameter and fills it with random numbers.

Syntax:

public virtual void NextBytes (byte[] buffer);

Here, buffer is the array of bytes to contain random numbers.

Exception: This method will give ArgumentNullException if the buffer is null.

Below programs illustrates the use of NextBytes() method:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the
// use of Random.NextBytes Method
using System;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Instantiate random number generator
        Random rand = new Random();
  
        // Instantiate an array of byte
        Byte[] b = new Byte[10];
  
        rand.NextBytes(b);
  
        // Print random numbers in the byte array
        Console.WriteLine("Printing random numbers"+
                              " in the byte array");
  
        for (int i = 0; i < 10; i++)
            Console.WriteLine("{0} -> {1}", i, b[i]);
    }
}

chevron_right


Output:

Printing random numbers in the byte array
0 -> 63
1 -> 166
2 -> 5
3 -> 212
4 -> 114
5 -> 94
6 -> 161
7 -> 4
8 -> 226
9 -> 46

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the
// use of Random.NextBytes Method
using System;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Instantiate random number generator
        Random rand = new Random();
  
        // Instantiate an array of byte
        Byte[] b = new Byte[10];
  
        rand.NextBytes(b);
  
        // Print random numbers in the byte array
        Console.WriteLine("Printing random numbers"+
                              " in the byte array");
  
        foreach(byte byteValue in b)
            Console.WriteLine("{0}", byteValue);
    }
}

chevron_right


Output:

Printing random numbers in the byte array
98
68
221
160
179
78
172
129
121
179

Reference:



My Personal Notes arrow_drop_up

Coder Machine Learner Social Activist Vocalist

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.