I have a function like this(foo): I need to compare the input string and perform a task accordingly . Task is same, but only for a selected set of values. For all other values do nothing.
function foo(string x)
{
if(x == "abc")
//do Task1
if(x == "efg")
//do Task1
if(x == "hij")
//do Task1
if(x == "lmn")
//do Task1
}
Is there any other means to do checking other than this? Or putting OR operator inside if?
What is the preferred way?
switchstatement is a good fit for such cases; it allows you to write the target values nicely separated and with a minimum of unnecessary boilerplate.if (new[] {"abc", "efg", "hij", "lmn"}.Contains(x)) { Task1(); }... Not sure myself, but it works.string[]does not actually contain a methodContains, so that works only because of Linq. Not that that is a problem. The pure array solution would beif (Array.IndexOf(new[] {"abc", "efg", "hij", "lmn"}, x) != -1) { ... }, but that looks quite awful.if(x.Is("abc", "efg", "hij", "lmn")) { }