Dutton

How to create an array with a lower bound other than zero in .Net

Did you know that you can create an Array with a lower bound other than zero in .Net?

A good friend of mine (cheers Jarek) showed me this a while back. I'm still yet to find a real-world application but it's interesting all the same.

Array has a method called CreateInstance, which is useful if you want to create an Array during run-time of a Type which might not be known beforehand. This will create an array of integers with length 5:

var array = Array.CreateInstance(typeof(int), 5);

One overload also lets you specify the lower bounds of the array. It is used to create multi-dimensional arrays, so you pass in arrays of lengths and bounds. This will create an array of integers, with length 50, indexed from 10.

var array = Array.CreateInstance(typeof(int), new int[] {50}, new int[] {10});

I suppose this may come in useful when trying to model an existing offset numbering scheme in your domain, but has anyone come across this or used it before?


Share this: