2

Just a basic if statement, trying to make it a little simpler and easier to read. Right now it reads:

  if ( myid == 1 || myid ==2 || myid == 10 || myid == 11 || myid == 12 || myid == 13 || myid ==14 || myid ==15)
  {
    ...
  }

I was thinking something like int[] ints = [1,2,10,11,12,13,14,15], then

  if (ints.Contains(myid))
  {
  }

I don't actually know if this is really easier to read, it's definitely shorter, performance differences are probably negligible on both.

Divi
  • 7,621
  • 13
  • 47
  • 63
Scott Selby
  • 9,420
  • 12
  • 57
  • 96

1 Answers1

5

Question is quite opinion-based, but if readability is a key factor, one option is to use an extension method

public static bool In<T>(this T x, params T[] set)
{
    return set.Contains(x);
}

which would allow you to write:

if (myid.In(1, 2, 10, 11, 12, 13, 14, 15))
{

}

I'll fill other options, just to give some sense of comparison (I'm certainly not advocating all of the next options)

Ugly, but works fine for one "continuous" sequence:

if ((myid >= 1 && myid <= 2) || (myid >= 10 && myid <= 15))
{

}

You can define your own Between extension method. Note: I would always forget if minVal or maxVal are inclusive or exclusive. (For example Random.Next uses minValue inclusive and maxValue exclusive) :

public static bool Between(this int number, int minVal, int maxVal)
{
    return number >= minVal && number <= maxVal;
}

Consider much better Between extension method, this is just a naive example. Now you can:

if (myid.Between(1, 2) || myid.Between(10, 15))
{

}

Or use native methods

if (new[]{1, 2, 10, 11, 12, 13, 14, 15}.Contains(myid))
{

}

Or

int[] expectedValues = {1, 2, 10, 11, 12, 13, 14, 15};
if (expectedValues.Contains(myid))
{

}
Community
  • 1
  • 1
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
  • that'll work - I wasn't trying to make an opinion based question , just couldn't remember if there was clearly a very simple way to check for a bunch of different casses that I was missing – Scott Selby Jul 02 '14 at 02:06
  • using a build-in function or custom extension method that does exactly the same is sometimes.. well. controversial. You can see [answers yourself](http://stackoverflow.com/q/16866174/1283124) – Ilya Ivanov Jul 02 '14 at 02:08
  • I dont't think anyone has the opinion that a very long string of `or` operators on one line is a good, readable and clean code. – v.oddou Jul 02 '14 at 02:11
  • @v.oddou I agree, opinions come into play when you are trying to decide either between `myid.In(1, 2, 10, 11, 12, 13, 14, 15)` or `new[]{1, 2, 10, 11, 12, 13, 14, 15}.Contains(myid)` or `ints.Contains(myid)` or `ints.In(myid)` – Ilya Ivanov Jul 02 '14 at 02:12