Tuesday, November 1, 2022

Generate Random Numbers in .NET6

 We can generate random number using the following code:

Console.WriteLine("Generate Randoms!");

var objRandom = new Random();

var myValue = objRandom.Next();

Console.WriteLine($"{myValue}");

In the above example, you obtain an int number as result.

You can use the methods NextBytes and NextDouble to obtain the results to obtain random bytes or random doubles values.


In .NET 6 you can use the class RandomNumberGenerator present in the namespace System.Security.Cryptography.


  Console.WriteLine("Generate Randoms in .NET 6!");

   var objRandom = RandomNumberGenerator.Create();

   var objBytes = new byte[sizeof(int)]; // 4 bytes

   objRandom.GetNonZeroBytes(objBytes);

    var myResult = BitConverter.ToInt32(objBytes, 0);

    Console.WriteLine($"{myResult}");

No comments:

Post a Comment

How to add the .NET MAUI App Accelerator in Visual Studio

 To add the .NET MAUI App Accelerator in Visual Studio, follow these steps: Prerequisites: Ensure you have Visual Studio 2022 (17.3 or lat...