Joey Weidman Joey Weidman - 2 months ago 5
C# Question

What are the alternatives to OR'ing multiple value options in an IF clause?

Is there any c# syntax that would make this if statement cleaner/shorter?

if (token == "(" || token == ")" || token == "+" || token == "-" || token == "*" || token == "/")
{
//do something
}

Answer

Like this:

// create a string with the valid chars
var tokens = "()+-*/";

// this will call the Contains method of the String class
if(tokens.Contains(token))
{
     //do something
}

Or with an array: (This way you can validate on multiple chars within a match. (not included on this example))

// create an array with the valid strings
var tokens = new [] { "(", ")", "+", "-", "*", "/" };

// this will call Contains method of the Enumerable class
if(tokens.Contains(token))
{
     //do something
}