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:
a
: Random Integer from 0 to (not-including) a
a
, b
: Random Integer from a to (not-including) b
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.
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
If you want to create a random boolean, use this code:
var random = new Random();
var randomBool = random.Next(2) == 1;