Robware Software by Rob

Fluent C# method for creating sequential numeric ranges

Here's a small method to aid test readability when dealing with sequential numeric ranges:

public static class IntExtensions
{
	public static IEnumerable<int> To(this int min, int max)
	{
		for (int i = min; i < max + 1; i++)
		{
			yield return i;
		}
	}
}

It can be used like so:

var range = 2.To(16);

You could have a test like:

var range = 2.To(16);

var expectation = new[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

range.Should().BeEquivalentTo(expectation);

In my case it was used for testing methods that group values in ranges by threshold values. Rather than typing out the ranges each time, I made this method to make it less tedious to both read and write.

Posted on Friday the 28th of February 2025