Home > OS >  How do you structure if statements with multiple values?
How do you structure if statements with multiple values?

Time:08-21

I'm trying to assign a boolean a false value if the int value day is the 31st, and the int value month is any of the following, 4,6,9,11.
What I currently have is not working, how should it be structured?

if (day == 31 && month == 4 || month == 6 || month == 9 || month == 11)
{
      validity = false;
} 

CodePudding user response:

Granted, I could go on about operator precedence (which one goes first), but really, you should never have to worry about that because you should always be very explicit about how you want something to be evaluated. Use your parentheses to do so.

You can use newer features of C# to make it even more clear what you're doing:

if ((day is 31) && (month is 4 or 6 or 9 or 11))

CodePudding user response:

All answers are valid, but here is my example if you want to shorten expression, what if you need to compare more month values, you can put all values in array and search if month value is contained in array.

if(day == 31 && new int[] { 4, 6, 9, 11 }.Contains(month))
{
}

Also you can create extension method name In and check if your month value is contained in array.

public static class Extensions
{
    public static bool In<T>(this T value, params T[] array)
    {
        return array.Contains(value);
    }
}

if (day.In(31) && month.In(4, 6, 9, 11))
{
}

But as I said this depends on you, use what is more readable to you or someone else who look at your code :)

  •  Tags:  
  • c#
  • Related