Using an &&
expression to join two comparisons is simply the most elegant way to do this. If you try using fancy extension methods and such, you run into the question of whether to include the upper bound, the lower bound, or both. Once you start adding additional variables or changing the extension names to indicate what is included, your code becomes longer and harder to read (for the vast majority of programmers). Furthermore, tools like Resharper will warn you if your comparison doesn't make sense (number > 100 && number < 1
), which they won't do if you use a method ('i.IsBetween(100, 1)').
The only other comment I'd make is that if you're checking inputs with the intention to throw an exception, you should consider using code contracts:
Contract.Requires(number > 1 && number < 100)
This is more elegant than if(...) throw new Exception(...)
, and you could even get compile-time warnings if someone tries to call your method without ensuring that the number is in bounds first.