Home > Enterprise >  Does it make sense to talk about a Minimum and a Maximum for Boolean variables in C#?
Does it make sense to talk about a Minimum and a Maximum for Boolean variables in C#?

Time:10-03

Does it make sense to talk about a minimum and maximum for boolean values in C# where by

false < true

minimum of the range is false and maximum of the range is true?

I mention C# specifically because some people mention the C/C context, where true/false map out to integers.

To me talking about a minimum and a maximum for boolean values makes no sense.

CodePudding user response:

Does it make sense to talk about a minimum and maximum for Boolean values in C#?

Yes, it makes sense. Although C# doesn't let you directly compare bool values using relational operators like < and >, the System.Boolean type implements the IComparable interface, so you can compare bool values using the CompareTo method. This method considers false to be less than true:

// Is false less than true?
Console.WriteLine(false.CompareTo(true) < 0);   // True

// Is true less than or equal to false?
Console.WriteLine(true.CompareTo(false) <= 0);  // False

// Is true greater than or equal to true?
Console.WriteLine(true.CompareTo(true) >= 0);   // True

Therefore:

  1. The minimum of a non-empty collection of bool values is false if any are false, and true otherwise.
  2. The maximum of a non-empty collection of bool values is true if any are true, and false otherwise.

This can be demonstrated by using the LINQ Min and Max extension methods:

using System.Linq;

Console.WriteLine(new[] { false, false }.Max());  // False
Console.WriteLine(new[] { false, true }.Min());   // False
Console.WriteLine(new[] { false, true }.Max());   // True
Console.WriteLine(new[] { true, true }.Min());    // True

CodePudding user response:

No, it does not make sense to talk about a minimum and maximum for boolean values in C#.

You will get below

Compilation error (line 9, col 12): Operator '<' cannot be applied to operands of type 'bool' and 'bool'

Find Complete Detail about Boolean Type Here

But in C# if convert false to int then it is 0 and true is 1 but it is not referring any minimum and maximum range. it just representation so 1 always greater than 0.

var r = Convert.ToInt32(false) < Convert.ToInt32(true);
      
    Console.Write(r);

  • Related