pencilCake
pencilCake

Reputation: 53253

Is this possible somehow in C# : if (a==b==c==d) {...}

Is there a quick way to compare equality of more than one values in C#?

something like:

if (5==6==2==2){

//do something

}

Thanks

Upvotes: 6

Views: 9545

Answers (4)

Zano
Zano

Reputation: 2761

In C#, an equality operator (==) evaluates to a bool so 5 == 6 evaluates to false.

The comparison 5 == 6 == 2 == 2 would translate to

(((5 == 6) == 2) == 2)

which evaluates to

((false == 2) == 2)

which would try to compare a boolwith an int. Only if you would compare boolean values this way would the syntax be valid, but probably not do what you want.

The way to do multiple comparison is what @Joachim Sauer suggested:

 a == b && b == c && c == d

Upvotes: 16

Francisco Soto
Francisco Soto

Reputation: 10392

public static class Common {
    public static bool AllAreEqual<T>(params T[] args)
    {
        if (args != null && args.Length > 1)
        {
            for (int i = 1; i < args.Length; i++)
            {
                if (args[i] != args[i - 1]) return false;
            }
        }

        return true;
    } 
}

...

if (Common.AllAreEqual<int>(a, b, c, d, e, f, g)) 

This could help :)

Upvotes: 15

Anemoia
Anemoia

Reputation: 8116

No this is not possible, you have to split it into separate statements.

if(x == y && x == z) // now y == z
{
}

Good luck

Upvotes: 5

Joachim Sauer
Joachim Sauer

Reputation: 308081

if (a == b && b == c && c == d) {
    // do something
}

Upvotes: 31

Related Questions