Alex Rivera | Logout

C#. Do if( a == (b or c or d)). Is it possible?

Asked 2010-07-14T08:04:50.190
28

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:

if( new [] {x,y,z}.Contains(a))

Are there other good ways?

Edit
Report

1 Answer

3

So, you want to replace a simple, efficent language construct that contains short-circuit optimisations into something much slower that has the potential for throwing exceptions?

However, if the items you want to compare against are not fixed in quantity, i.e. at run time it could be t,u,v,w,x,y,z,etc..., then the Collection.Contains method is the only option, but then you'd be passing collection objects around rather than individual values and so there's little memory allocation ovrehead.

If you've got a large number of items to compare 'a' against, but the items are not dynamic at run time then a switch statement might be a better fit.

answered 2010-07-14T08:17:30.543

Your Answer