- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Random.NextBytes() Method in C#
The Random.NextBytes() method in C# is used to fill the elements of a specified array of bytes with random numbers.
Syntax
The syntax is as follows −
public virtual void NextBytes (byte[] buffer);
Above the buffer is the array of bytes.
Example
Let us now see an example −
using System; public class Demo { public static void Main(){ Random r = new Random(); Random r2 = new Random(); Random r3 = new Random(); Byte[] arr = new Byte[5]; r3.NextBytes(arr); Console.WriteLine("Random numbers....."); for (int i = 1; i <= 5; i++) Console.WriteLine(r.Next()); Console.WriteLine("
Random numbers from 1 to 10....."); for (int i = 1; i <= 5; i++) Console.WriteLine(r2.Next(10)); Console.WriteLine("
Random numbers in the byte array..."); for (int i = 0; i < arr.GetUpperBound(0); i++) Console.WriteLine(arr[i]); } }
Output
This will produce the following output −
Random numbers..... 2081486546 329484380 1639318640 1499756340 2122408387 Random numbers from 1 to 10..... 9 1 7 6 9 Random numbers in the byte array... 210 92 112 52
Example
Let us now see another example −
using System; public class Demo { public static void Main(){ Random r = new Random(); Byte[] arr = new Byte[2]; r.NextBytes(arr); Console.WriteLine("Random numbers in the byte array..."); for (int i = 0; i < 2; i++) Console.WriteLine(arr[i]); } }
Output
This will produce the following output −
Random numbers in the byte array... 173 11
Advertisements