Is there any way in C# to shorten this?
For example, how would you shorten this:
bool a = x == "YES" || x == "NO"
Code I'm writing:
public static bool isYESNO(string x)
{
return x == "YES" || x == "NO";
}
Is there any way in C# to shorten this?
For example, how would you shorten this:
bool a = x == "YES" || x == "NO"
Code I'm writing:
public static bool isYESNO(string x)
{
return x == "YES" || x == "NO";
}
You can write the extension method:
public static class Extensions
{
public static bool In<T>(this T item, params T[] items)
{
return items.Contains(item);
}
}
And then use it like this:
var x = "YES";
bool a = x.In("YES", "NO");
Console.WriteLine(a);
It might be not too helpful if you have just couple of items, but it you have a lot of them it makes syntax shorter:
bool a = x.In("YES", "NO", "TRUE", "FALSE", "SOME OTHER VALUE");
You can try like
if (new[] {"YES", "NO"}.Contains(x))
This may be useful when you have multiple values to check in your OR condition. Something like
if (new[] {"YES", "NO", "value1", "value2", "value3", "value4"}.Contains(x))
In your present case your way of doing is quite readable and short.
Suppose you only want to check two items like what is shown in your example, I think your method is already pretty short. However, if you have a lot of items (like 10 items) for checking, consider using LINQ Contains
for comparison:
string[] correctItems = new string[] { "YES", "NO", "bla1", "bla2", "bla3", "bla4", "bla5", "bla6", "bla7", "bla8" };
bool a = correctItems.Contains(x);