Condividi tramite


Arrays with non-zero upper and lower bounds...

In the comments to my post on zero and one based arrays, several people mentioned that they wanted to be able to have collections that ran from 4 to 10, or from 1900 to 2004 for years. Consider the following:

 public class YearClass
{
   const int StartDate = 1900;
   const int EndDate = 2050;
   int[] arr = new int[EndDate - StartDate + 1];

   public int this[int num]
   {
      get { return arr[ num - StartDate]; }
      set { arr[num - StartDate] = value; }
   }
}

public class Test
{
    public static void Main()
    {
        YearClass yc = new YearClass();
        yc[1950] = 5;
     }
}

 

I think that gives you the user model that you want.

Comments

  • Anonymous
    March 18, 2004
    The comment has been removed
  • Anonymous
    March 18, 2004
    In order to avoid a System.IndexOutOfRangeException, I would check the index to insure that it is within the appropriate range.
  • Anonymous
    March 18, 2004
    public class OffsetArray<T>
    {
    readonly int start;
    readonly int end;
    T[] arr;

    public OffsetCollection<T>( int start, int end)
    {
    this.start = start;
    this.end = end;
    this.arr = new T[ end - start + 1];
    }

    public T this[int num]
    {
    get { return arr[ num - start]; }
    set { arr[num - start] = value; }
    }
    }

    You'd probably want to sanity check start and end in the constructor. Requesting an index that's out of range should throw an IndexOutOfRangeException, IMHO.
  • Anonymous
    March 18, 2004
    You know I looked at that and thought "why didn't I think of that?" The reason is of course that I've been programming too long with the old model of programming and things like this, which should probably be obvious to someone who has really internalized OOP, don't come natural to me. This will get me thinking in some new directions. Thanks.
  • Anonymous
    March 18, 2004
    Steve, in most cases, I would tend to agree with you that throwing an IndexOutOfRangeException would be appropriate. However, in this case, it would be more appropriate, IMHO, to raise a custom expression like DateOutOfRangeException. This gives the user of the class a better clue as to what the problem is.
  • Anonymous
    March 19, 2004
    What do templates have to do with C#? Surely they aren't going to show up in future versions since that would uglify the currently readable C# syntax. Eric's solution is ok for now. Just move that into the core and call it a day.
  • Anonymous
    March 19, 2004
    Shouldn't it be StartYear, EndYear and YearOutOfRangeException? I think IndexOutOfRangeException is just fine, because I am after all indexing it.
  • Anonymous
    March 20, 2004
    You can also use Array.CreateInstance(Type, int[], int[]) to create an array with a specified element type, and specified dimensionality, lengths, and lower bounds.