9

Do i have to set my if statement as

if(Test == "test1" || Test == "test2" || Test == "test3")
{
    //do something
}

Is there a way to have something like

if(Test == "test1":"test2":"test3")
Nas Banov
  • 28,347
  • 6
  • 48
  • 67
MrM
  • 21,709
  • 30
  • 113
  • 139

3 Answers3

17

Yes.

if (new [] { "test1", "test2", "test3" }.Contains(Test))

You can even write an extension method:

public static bool IsAnyOf<T>(this T obj, params T[] values) { 
    return values.Contains(T); 
}

if (Test.IsAnyOf("test1", "test2", "test3"))

For optimal performance, you can make overloads that take two or three parameters and don't use arrays.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
17

There is nothing wrong with the code that you have written. It is easy to understand, but you could try:

switch (Test)
{
   case "test1":
   case "test2":
   case "test3":
      //your code here
      break;
   default :
      //else code
      break;
 }

As you can see, this considerably more verbose than your original if statement and not immediately obvious what it is for, but it is an answer of sorts. And it will compile to quite efficient intermediate code. In fact, if this post is to be believed, then it could compile to more efficient code than the if statement in your post, depending on whether the values are considered "adjacent" by the compiler.

Community
  • 1
  • 1
Daniel Dyson
  • 13,192
  • 6
  • 42
  • 73
  • 4
    +1 for not using `Contains` .. talk about teaching bad habits; sheesh. – Ben M Jul 06 '10 at 17:12
  • 1
    "bad habits" - how so? `Regex.Match(Test, "test[1-3]")` would be a bad habit :) – Tim Robinson Jul 06 '10 at 17:27
  • @Tim Robinson: I just mean that using `Contains` (especially in combination with a throwaway allocation) for basic control flow is total overkill. – Ben M Jul 06 '10 at 17:43
  • 2
    For this it is. Depends on what the real values are (presumably not "test1", "test2", "test3") and what the OP expects to add in future. The array can be `private static readonly`. – Tim Robinson Jul 06 '10 at 17:55
  • I was vague on the fact that I was looking at if statements only. I use the switch case, which works pretty well. Now I know that I was using good practice all along. The answer is appreciated. – MrM Jul 14 '10 at 12:05
  • 2
    In that case you should edit your question or change which answer you accepted. Otherwise, users who come across this will be mis-led into thinking that the acceepted answer is the better one for them. – Daniel Dyson Jul 14 '10 at 12:15
5

What you could do to shorten your statement a little is the following:

if (new[] { "test1", "test2", "test2" }.Contains(Test))
{
    ...
}
Ronald Wildenberg
  • 31,634
  • 14
  • 90
  • 133