generate a random boolean in csharp

To generate a random boolean in C#, you can use the Random class provided by .NET framework. The Random class has a Next method that generates a random integer between specified minimum and maximum values.

Here's a simple method to generate a random boolean:

main.cs
public static bool GetRandomBool()
{
    Random random = new Random();
    return random.Next(2) == 0;
}
105 chars
6 lines

Explanation:

  1. We create an instance of Random class.
  2. The Next method of Random class generates a random integer between 0 (inclusive) and 2 (exclusive). This means it will return either 0 or 1 randomly.
  3. We then simply compare the output of Next method with 0 and return the boolean value accordingly.

You can use this method anywhere in your code to get a random boolean value.

related categories

gistlibby LogSnag