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 upload app to macOS

1. Open Terminal Press Cmd (⌘) + Space , type Terminal , and hit Enter . 2. Navigate to Your Build Output Directory Your .app file is likel...