Generating Random Booleans In C# & .NET
[C#, .NET]
Over the past week, we have been looking at some of the challenges of generating random values of the various integral types from bytes
to unsigned 64 bit integers
.
There is, however, a case that you will encounter - generating a random boolean
.
This is a common use case for scenarios where you need to generate a choice, like a coin toss.
A simple way to achieve this is to use Random.Next(), and pass an upper bound of 2
.
This means you will either get back a 0
or a 1
, that you can map to false
and true
.
Random.Shared.Next(2) == 0;
Another is to use Random.NextDouble(), which returns a double
value between 0.0
and 1.0
, and check if that is < 0.5
.
Random.Shared.NextDouble() < 0.5;
For most purposes, these techniques are good enough.
If, however, for security purposes, you require a cryptographically secure random generator, you can use the RandomNumberGenerator for this purpose, using its Fill method to generate random values into a buffer.
Your code would look like this:
using System.Security.Cryptography;
// Create a single random byte buffer
Span<byte> buffer = stackalloc byte[1];
// Fill buffer with the random number generator
RandomNumberGenerator.Fill(buffer);
// Use the lowest bit to determine true or false
var randomBoolean = (buffer[0] & 1) == 1;
// Output
Console.WriteLine(randomBoolean);
TLDR
The Random
class can also be used to generate random boolean
values. For cryptographically secure purposes, the RandomNumberGenerator
can be used.
The code is in my GitHub.
Happy hacking!