Home > .net 3.0, .net 3.5, c#, LINQ, Microsoft, Visual Studio 2005, Visual Studio 2008 > A Flexible “Is In Range” Extension Method

A Flexible “Is In Range” Extension Method

May 11, 2009

I’m working out some business rules for an application that allows the end user to specify whether or not to direct records by the first letter of the last name of a student or by the grade of the student.

The quick extension method looks like this:

public static bool IsInRange<T>(this T value, T start, T end)

where T: IComparable<T>

{

return value.CompareTo(start) >= 0 && value.CompareTo(end) <= 0;

}

Our tests:

[Fact]

public void IsInRange_returns_correct_boolean_for_comparison()

{

9.IsInRange(1, 10).ShouldBeTrue();

“L”.IsInRange(“A”, “J”).ShouldBeFalse();

“A”.IsInRange(“A”, “A”).ShouldBeTrue();

“B”.IsInRange(“A”, “A”).ShouldBeFalse();

12302.IsInRange(1, 10).ShouldBeFalse();

 

“Bob”.IsInRange(“A”, “A”).ShouldBeFalse();

“Smith”.IsInRange(“A”, “Z”).ShouldBeTrue();

}

Everything works well… I haven’t tested all of the permutations and types yet… but it gets me out of the jam I’m in right now.

Is there a better way?😀

  1. May 11, 2009 at 5:37 pm

    I LIKE that! Thanks!

    ~Lee

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: