2
votes

I have three boolean variables. I need to check if all three are true or all three are false.

I can do this in a 'dummy' way:

bool areSame = false; 
if(a && b && c)    
    areSame = true; 
else if (!a && !b && !c)
    areSame = true;

I'd like to know if there is another more elegant solution.

7

7 Answers

6
votes

You can use the equality operator on booleans too:

bool areSame = (a == b) && (a == c);
6
votes

Sure, you're only comparing three here, but what about the future? You might have to compare ten booleans to each other somewhere down the road.

    class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(false.AllEqual(false, false)); 
                Console.WriteLine(true.AllEqual(false, false));
                Console.WriteLine(true.AllEqual(true, false));

                bool a = true;
                bool b = false;
                bool c = true;
                Console.WriteLine(a.AllEqual(b, c));
                b = true;
                Console.WriteLine(a.AllEqual(b, c));
                Console.ReadLine();
            } 
        }

        static class Extensions
    {
        static public  bool AllEqual(this bool firstValue, params bool[] bools)
        {
            return bools.All(thisBool => thisBool == firstValue);
        }
    }
4
votes

how about using this?

areSame = (a == b && b == c);
1
votes

What about:

bool areSame = (a && b && c) || (!a && !b && !c) ? true : false;
0
votes

What about this approach? It will allow you to pass in as many bools and see if the min number of trues are met.

public static bool AreMinNumberOfTruesMet(int minNumOftrue, params bool[] bools)
{
    var totalTrue = bools.Count(boolean => boolean == true);

    return totalTrue >= minNumOftrue;
}
0
votes

Or in one line :

bool allSame = !bools.Any(b => b != bools[0])
-1
votes
//all same
bool allSame = a == b == c == d;

//all false
bool allFalse = a == b == c == d == false;