T-SQL has a between statement to make it easier to determine if a test object occurs between two other objects. I needed similar functionality in C# but I didn't know what the type the objects would be; however, I did know they would always be IComparable. Obviously, there's no real need for an extension method here, but it did make things a bit more convenient.Like T-SQL, the between extension method is inclusive and the start parameter doesn't have to be lower than the end parameter.
Here's what some test cases look like:
5.Between(1, 10) // true 5.Between(10, 1) // true 5.Between(10, 6) // false 5.Between(5, 5)) // true
Here's the method:
public static bool Between<T>(this T target, T start, T end)
where T : IComparable
{
if (start.CompareTo(end) == 1)
return (target.CompareTo(end) >= 0) && (target.CompareTo(start) <= 0);
return (target.CompareTo(start) >= 0) && (target.CompareTo(end) <= 0);
}
I really appreciate comments so please feel free to comment on my posts. Whether you agree or disagree, I'd love to hear from you. Also, feel free to link back to your own blog in your comments. You can even subscribe to an RSS feed of the comments on this thread.
© 2008 , D. Patrick Caldwell, President, Autopilot Consulting, LLC
© 2008 , D. Patrick Caldwell, President, Autopilot Consulting, LLC
click for more information
0 comments:
Post a Comment