Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test that multiple booleans have identical values in c#?

Is there a shorter way of testing the following:

if (!((a == b) && (a == c) && (a == d) && (a == e) && (a == f)))

I ended up writing a method that lets me do this

if (!AllEqual(new[] { a, b, c, d, e, f }))

That feels nicer and is a lot more readable, but I'm wondering if there is something in the framework that does this already?

like image 566
My Other Me Avatar asked Nov 10 '10 07:11

My Other Me


1 Answers

Well for one thing, you can use a parameter array to make it simpler:

public static bool AllEqual<T>(params T[] values)
...


if (AllEqual(a, b, c, d, e, f))
{
    ...
}

I don't think you'll find anything simpler than that, to be honest. I haven't seen this anywhere else, or in the framework. Well, I suppose there's one thing you could do in LINQ:

if (new { a, b, c, d, e, f }.Distinct().Count() == 1)

But that's pretty horrible :)

A slightly more efficient version of that is:

if (!(new { a, b, c, d, e, f }).Distinct().Skip(1).Any()))

... which will return false as soon as it finds the second distinct element. With only 6 elements I don't think it's worth worrying though :)

like image 57
Jon Skeet Avatar answered Sep 21 '22 12:09

Jon Skeet