Generate Random Numbers with .NET 6




Published on

October 23, 2022

Since the first release of .NET Framework, a class called Random was shipped. This class is still present in .NET 6 and it works like the first release.

Generating a random number is very easy, as in the following code:

var random = new Random();
var value = random.Next();
return value;

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.

This random values are random but not so really random as the documentation say in this page: https://learn.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=netframework-4.8 (search for pseudo-random word).

The solution

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

This class generates cryptographically secure values and for this reason are not predictable by you or by someone else.

You can use the sizeof to determinate the output type of the random value and the BitConverter to convert the random bytes to the value.

Basically, you can extend the code below.

Console.WriteLine("Generate Randoms!");

var random = RandomNumberGenerator.Create();
var bytes = new byte[sizeof(int)]; // 4 bytes
var result = BitConverter.ToInt32(bytes);


Enjoy the real random values!

React, comment and follow on