6

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

pencilCake
  • 51,323
  • 85
  • 226
  • 363

4 Answers4

31
if (a == b && b == c && c == d) {
    // do something
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 9
    13 upvotes in 52 minutes? It's in fact the easy questions that bring the rep. – Joachim Sauer Apr 30 '10 at 09:55
  • 1
    And the short concise answers? :-) – Zano Apr 30 '10 at 10:54
  • 3
    @Joachim: Don't tell me that you needed 24k rep to realize that ... ^^ – tanascius Apr 30 '10 at 11:29
  • @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 Apr 30 '10 at 11:29
  • 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 Apr 30 '10 at 11:41
  • 1
    My guess is that people that cannot understand the specialized subjects you refer to simply do not vote. – Francisco Soto Jul 16 '10 at 22:59
16

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
  • 2,595
  • 27
  • 33
15
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 :)

Steven
  • 166,672
  • 24
  • 332
  • 435
Francisco Soto
  • 10,277
  • 2
  • 37
  • 46
  • 5
    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 Apr 30 '10 at 11:50
5

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

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

Good luck

Anemoia
  • 7,928
  • 7
  • 46
  • 71