views:

452

answers:

5

Hi,

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

+23  A: 
if (a == b && b == c && c == d) {
    // do something
}
Joachim Sauer
13 upvotes in 52 minutes? It's in fact the easy questions that bring the rep.
Joachim Sauer
And the short concise answers? :-)
Zano
@Joachim: Don't tell me that you needed 24k rep to realize that ... ^^
tanascius
@tanascius: of course I've had my suspicion, but this simply was an impressive demonstration of the fact. I've written more than a few answers that I felt were very good and thorough and got me only one or two upvotes.
Joachim Sauer
Yes, I still find it amazing myself that my simplest answers (http://stackoverflow.com/questions/2222831/when-is-a-class-too-long/2222856#2222856) sometimes get a very high rating, while the answers on specialized subjects (http://stackoverflow.com/questions/2677652/using-using-to-dispose-of-nested-objects/2678242#2678242, http://stackoverflow.com/questions/2266168/ms-validation-block-or-workflow-rules-engine/2273940#2273940) get almost no rating. Popular subjects get higher rating easily.
Steven
My guess is that people that cannot understand the specialized subjects you refer to simply do not vote.
Francisco Soto
+5  A: 

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

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

Good luck

Snake
+1  A: 

There is no direct way to do it using C#, but you can go with some helper class. Check out this VB.NET topic dedicated to this problem http://stackoverflow.com/questions/686485/vb-net-test-multiple-values-for-equality

iyalovoi
+10  A: 

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
Zano
+1 for explaining why it doesn't work in c#
Richard Szalay
+11  A: 
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 :)

Francisco Soto
In the `if`, I would use `!args[i].Equals(args[i - 1])`. This allows use of reference types that implement `IEqualityComparer`. By default `==` compares for reference equality on ref types, not its underlying value.
spoulson