Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have an if statement like this? If Test = "test1" or "test2" or "test3" without going the long way?

Tags:

c#

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")
like image 477
MrM Avatar asked Jul 06 '10 17:07

MrM


3 Answers

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.

like image 128
SLaks Avatar answered Nov 14 '22 09:11

SLaks


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.

like image 17
Daniel Dyson Avatar answered Nov 14 '22 09:11

Daniel Dyson


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

if (new[] { "test1", "test2", "test2" }.Contains(Test))
{
    ...
}
like image 5
Ronald Wildenberg Avatar answered Nov 14 '22 11:11

Ronald Wildenberg