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
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
No this is not possible, you have to split it into separate statements.
if(x == y && x == z) // now y == z
{
}
Good luck
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
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 bool
with 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
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 :)