Is there another way to write something like this:
if (a == x || a == y || a == z)
One way that I found is doing it like this:
Your solution to rewrite it as
if( new [] {x,y,z}.Contains(a))
is not a good move.
You've take a simple efficient logical operation, which every programmer easily understands and which contains short-circuiting logic to speed it up and instead you've produced code that requires a moment to understand and which is considerably less efficient.
Sometimes your fellow engineers will prefer it if you don't try to be "clever"!
if(a==x?true:a==y?true:a==z?true:false)
For instance, your logic is like that:
if(a==x || a== y|| a==z)
{
DoSomething();
}
else
{
DoOtherThings();
}
will equivalent to:
if(a!=x&& a != y && a!= z)
{
DoOtherThings();
}
else
{
DoSomething();
}
Cheers.
Consider a case where a == x, and y and z are slow-to-evaluate, expensive functions.
if(a == x || a == y || a == z)
you have the benefit of the short-circuit ||
-operator, so you y and z won't be evaluated. new[] { x, y, z }
- y and z will be evaluated every time. The 'trick' with .Contains()
would be more useful if there was an elegant syntax to create lazy-evaluated sequence (IEnumerable<T>
). i.e. something like yield return x; yield return y;...
, but inlined and shorter.
Why would you need yet another way? Since it isn't a matter of functionality, I would guess the point is to improve readability.
If you have a few variables with meaningful names, it would be more readable to just compare by using ==
. If you have more, you can use Contains
against a list as in your other sample.
Yet another way would be comparing against enum flags:
[Flags]
public enum Size
{
Small = 1,
Medium = 2,
Large = 4
}
And then to find out if mySize
is in Small
or Medium
:
selectedSizes = Size.Small | Size.Medium;
mySize = Size.Small;
if (mySize & selectedSizes)
{
...
}