DEV Community

Cover image for Generate Random Numbers with .NET 6
Emanuele Bartolesi
Emanuele Bartolesi

Posted on

3

Generate Random Numbers with .NET 6

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;
Enter fullscreen mode Exit fullscreen mode

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}");
Enter fullscreen mode Exit fullscreen mode

Enjoy the real random values!

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video πŸ“ΉοΈ

Top comments (2)

Collapse
 
matigramirez profile image
Matias β€’

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.

Collapse
 
a510 profile image
Ahmad Ibrahim β€’

You can also use "RandomNumberGenerator.GetInt32" directly.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay