Aarron Dixon
Aarron Dixon

Reputation: 97

How do I assign a range of numbers to an if statement in C#?

I want an if statement to activate over a certain range of number values and it's not working. Currently coding:

if (DateTime.Now.Minute == 20 - 39)
            lblMA2.BackColor = Color.Blue;
        else
            lblMA2.BackColor = Color.Gray;

The current time as of posting is within that range, and my label is staying gray. The same code works when I plug in an exact value. It'll turn blue as the minute hits, then gray as it passes. I plug in the range, and nothing.

Can anyone help me make it work without having to type in an extra 36 lines of code?

Thanks!

Upvotes: 1

Views: 1364

Answers (2)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

Use if (Enumerable.Range(20, 19).Contains(DateTime.Now.Minute))

Right now you're comparing DateTime.Now.Minute with 20 - 39 which is -19.

My solution creates a collection that contains the values from 20 to 39 and checks if the current minute is inside this collection.

Or you can just check if the minute is more than 20 and below 39 (which should be preferred, see the explanation by Konrad in the comments).

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

To check if a number falls within a particular range, use && on two conditions - the less than and the greater than, like this:

if (DateTime.Now.Minute >= 20 && DateTime.Now.Minute <= 39) {
    ...
}

&& means "AND". The composite condition evaluates to true when the left side evaluates to true, and then the right side also evaluates to true. The right side is evaluated only when the left side is true.

Upvotes: 3

Related Questions