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
random.GetNonZeroBytes(bytes);
var result = BitConverter.ToInt32(bytes);
Console.WriteLine($"{result}");
Enjoy the real random values!
Top comments (2)
Note that true randomness can't be achieved so generating "real random values" isn't quite possible.
RandomNumberGenerator
will still generate pseudo-random numbers but, as you said, they're cryptographically secure and are the way to go when dealing with security.Random
was updated in .NET Core and doesn't work in the same way as the old .NET Framework version, so it's still a viable option when security isn't a concern, in fact,RandomNumberGenerator
has some performance implications which should be taken into account when producing significant amounts of random numbers.You can also use "RandomNumberGenerator.GetInt32" directly.