Random boolean in C#

Are you creating a game where something needs to happen...or not happen randomly? Or you want to distribute things to one list or the other at random? What you want is a random boolean. C# offers no such thing. But after reading this article, you are able to create a random boolean with two lines of code!

C# comes with a Random class that provides all sorts of things. Integers from min to max, doubles, bytes and other exciting values. But what if you just want a simple Yes or No? You guessed it. Since booleans themselves are nothing but zeros and ones, we can just create a range of numbers to reflect a boolean.

The Random Class has a function Next that takes 0, 1 or 2 arguments:

That means that if we call Next(2), it should give us integers 0 and 1.

Let’s run this code:

var random = new Random();
for (int i = 0; i < 1000; i++)
{
    var b = random.Next(2);
    Console.Write(b);
}

Output:

11001100110100010...0001101001110011111011101101

Looks like something you could use to create booleans.

Create a random bool from a random 0 or 1

All you need to do to create a random boolean from an integer, is to convert its value to a boolean like this:

var randomBool = random.Next(2) == 1; // 0 = false, 1 = true;

Let’s run this code 20 times to see what happens:

var random = new Random();
for (int i = 0; i < 20; i++)
{
    Console.WriteLine(random.Next(2) == 1);
}

Note how the Random class only needs to be created once. Your can pass it around in your app and/or store it in a member variable.

Output:

True
False
False
True
True
False
False
True
False
False
True
True
False
False
False
True
True
False
False
False

Final code

If you want to create a random boolean, use this code:

var random = new Random();
var randomBool = random.Next(2) == 1;
Written by Loek van den Ouweland on October 01, 2019. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.