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?
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))
{
}
What about an extension method?
public static class Extensions
{
public static bool IsOneOf<T>(this T input, params T[] possibilites)
{
bool result = possibilites.Contains(input);
return result;
}
}
You could then rewrite your code to look like this:
string input = textBox1.Text;
if(input.IsOneOf("apple", "orange", "banana"))
{
// ....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With