Support for range in programming languages


The .NET platform and the languages on top of it have limited or no support for range of values. Data ranges are one of the most common data-types and somehow it’s not there. Funnily most programmers do not even seem to miss it (unless of course if you have used Ruby).

How would you specify a valid range of age and validate user data against it? If you know the maximum and minimum values, at max you’d define a MaxAge and MinAge consts and strew the code with if(age < MinAge|| age >MaxAge). Or maybe you’ll define a class to encapsulate this and add a IsValid method.

However, in Ruby, Range is a standard DataType like say string. To do the above processing you’d do

age = 1..120

print age.include?(50)
print age.include?(130)

print age === (50) # more easier way to do include? test using the === operator

So intuitively you create a range using start..stop.

Creating a range of data is also very simple. Say you want to generate the column numbers for an excel sheet, you’d do the following

column = 'A'..'ZZ'

column.to_a # creates an array of all the values

column.each {|v| puts "#{v}\n"}

Similarly ranges can be easily created for any class by implementing some special methods. On ruby the support of Range is in the compiler and makes the code very easy to develop and intuitive.

>>Cross posted here

Comments (5)

  1. Tim says:

    I guess the closest you can get, in C# at least, is a generic Range type, something like:

    public class Range<T>


    public T Min { get; set; }

    public T Max { get; set; }

    public Range(T min, T max)


    Min = min;

    Max = max;


    public bool Includes(T value)


    return (value >= Min && value <= Max);



    Then you can write code like:

    Range<int> age = new Range<int>(1, 120);



    Agreed, it’s not quite as compact as the Ruby code, but it’s not too bad!

  2. That’s just a type and can be used from any .NET language 🙂

  3. Dilip says:

    As usual sometime in the past Don Box has bent C# to behave like Ruby.

    See here:

  4. Joe Chung says:

    Enumerable.Range is available in the System.Linq namespace.

    Enumerable.Range(1, 150) => 1..150