C#. Do if( a == (b or c or d)). Is it possible?
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"!
I often use an extension method that mimics SQLs IN
:
public static bool IsIn<T>(this T obj, params T[] collection) {
return collection.Contains(obj);
}
That way I can do
if(a.IsIn(b, c, d)) { ... }
You have the classic switch statement :
switch(a) {
case x:
case y:
case z:
// Do stuff
break;
}
Just for fun:
using System;
static class Program {
static bool In(this object obj, params object[] values) {
foreach (object value in values) {
if (obj.Equals(value)) {
return true;
}
}
return false;
}
static void Main(string[] args) {
bool test1 = 3.In(1, 2, 3);
bool test2 = 5.In(1, 2, 3);
}
}
But I really think that the best way is to write the plain check
if(a == x || a == y || a == z)
As everybody will understand immediately what it does.