How to elegantly check if a number is within a range?

Sergio Tapia picture Sergio Tapia · Jul 6, 2010 · Viewed 383.4k times · Source

How can I do this elegantly with C# and .NET 3.5/4?

For example, a number can be between 1 and 100.

I know a simple if would suffice; but the keyword to this question is elegance. It's for my toy project not for production.

This questions wasn't about speed, but about code beauty. Stop talking about efficiency and such; remember you're preaching to the choir.

Answer

Dustin Laine picture Dustin Laine · Jul 6, 2010

There are a lot of options:

int x = 30;
if (Enumerable.Range(1,100).Contains(x))
    //true

if (x >= 1 && x <= 100)
    //true

Also, check out this SO post for regex options.