Is there a way to shorten the condition if it always compares to the same thing?

c#

Solution

Your condition says: I'm true if I match any of the predefined values. In other words if I'm an element of a predefined set which is semantically the `Contains` method:

if (new [] { "apple", "orange", "banana" }.Contains(x))
{

}

Using an array provides much more flexibility in the future. You can extract it out, reuse it, store it, chache it etc. I always use "arrays and loops" when I have to deal with more than 2 known values.

Note: As Scott Chamberlain pointed out in the comments with using `HashSet<T>.Contains` greatly improves the performace:

var values = new HashSet<string> { "apple", "banana", "orange" };
if (values.Contains(x))
{

}

Problem

I have always found it annoying when I need to write a condition that compares the same item over and over again since I would have the type the item so many times: ``` string x = textBox1.Text; if (x == "apple" || x == "orange" || x == "banana" ...) ... ``` I want something like this (but of course this is not correct syntax): ``` if (x == "apple" || "orange" || "banana" ...) ``` Is there a solution other than using an array of the strings?

Original source

Related problems