Int32 RangeTo() method

This little snippet, inspired by Ruby’s Range() method, allows you to do stuff like this;

foreach (int rownum in 0.RangeTo(1)) {
    //dostuff
}

I haven’t done any performance metrics yet, but I like the removal of human error in using this for iterations over arrays and datatables.
Here’s the extension class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System
{
	public static class Int32Extensions
	{
		///
<summary> /// Returns a sequence of integers from one to the other.
 /// Default end point is 0.
 /// </summary>
		///
		///
		///
		public static int[] RangeTo(this int startPoint, int endPoint = 0, bool inclusive = true)
		{
			int length = Math.Abs(startPoint - endPoint);
			if (inclusive) length += 1;

			var returnValue = new int[length];

			if (startPoint > endPoint)
			{
				for (int i = 0; i < length; i++)
				{
					returnValue[i] = startPoint - i;
				}
			}
			else
			{
				for (int i = 0; i < length; i++)
				{
					returnValue[i] = startPoint + i;
				}
			}
			return returnValue;
		}
	}
}

Advertisements

About this entry