Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply multiple operands to a single operator?

Tags:

operators

c#

How to apply multiple operands to a single operator?

An example:

instead of

if (foo == "dog" || foo == "cat" || foo == "human")

I can have the following or similar:

if (foo == ("dog" || "cat" || "human"));
like image 730
KMC Avatar asked Apr 27 '12 10:04

KMC


1 Answers

Your first version already includes multiple operators in one expression. It sounds like you want to apply multiple operands ("dog", "cat", "human") to a single operator (== in this case).

For that specific example you could use:

// Note: could extract this array (or make it a set etc) and reuse the same
// collection each time we evaluate this.
if (new[] { "dog", "cat", "human" }.Contains(foo))

But there's no general one-size-fits-all version of this for all operators.

EDIT: As noted in comments, the above won't perform as well as the hard-coded version.

like image 151
Jon Skeet Avatar answered Nov 02 '22 16:11

Jon Skeet