fearofawhackplanet
fearofawhackplanet

Reputation: 53388

chaining bools in C#

int a, b, c, d, e;
a = b = c = d = e = 1;

if ((a==b) && (b==c) && (c==d) && (d==e))
{
    Console.WriteLine("that syntax is horrible");
}

is there a more elegant way to test multiple equality as above?

maybe an AreEqual(params obj[]) or something? I had a google but didn't find anything.

Upvotes: 2

Views: 401

Answers (5)

Aviad P.
Aviad P.

Reputation: 32639

A possible implementation of AreEqual(params object[] objects):

(Following Jon Skeet's advice, here's a generic version)

bool AreEqual<T>(params T[] objects)
{
    if (objects.Length <= 1) return true;
    return objects.Skip(1).All(x => x.Equals(objects[0]));
}

The Skip(1) is not strictly necessary either.

Upvotes: 10

mcintyre321
mcintyre321

Reputation: 13306

This is fun

int a, b, c, d, e;
a = b = c = d = e = 1;

if ((a & b & c & d) == e)
{
    Console.WriteLine("that syntax is horrible");
}

and this is maybe better

int a, b, c, d, e;
a = b = c = d = e = 1;
if (new[] {a, b, c, d, e}.All(i => i == a))
{
    Console.WriteLine("Funky chicken");
}

Upvotes: 0

Jamie Ide
Jamie Ide

Reputation: 49261

If you're comparing simple types and you only have a few use cases then you could create a few utility methods such as:

    bool AllEqual(int first, params int[] numbers)
    {
        return numbers.All(x => x == first);
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

Here's a generic version which will avoid boxing (and be more type-safe at compile time):

public static bool AllEqual<T>(T firstItem, params T[] items)
{
    // Omitted error checking
    EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    foreach (T item in items)
    {
        if (!comparer.Equals(firstItem, item))
        {
            return false;
        }
    }
    return true;
}

Note that this won't be as convenient if you really want to pass a bunch of values you've already got in an array, but avoids problems with empty arrays - and means you don't have any redundant comparisons.

Upvotes: 4

Noon Silk
Noon Silk

Reputation: 55082

No, that's the most reasonable way (i mean the most readable, which is the most important).

The real question is, why do you need to do that? It seems like a bad design in the first place ...

Upvotes: 3

Related Questions