C# Array with specific LowerBound

34 Views Asked by At

This question for learning C#, and not a real problem. I was reading in C# that you can create an Array with custom LowerBound so it won't start from Zero. I thought this might be useful where I can store objects with numbers starting from n -> to m. Like for example In U.S address we have house numbers on a street goes as example from 1022 to 1066.

Right now I am using Dictionary<int, HouseInfo> to represent that data structure, where the key is the house number.

I thought it will be nice if I replace it with an array with Lower Bound equal to the first house number, so I won't make it on the size of the biggest house number, and when I use :

array[lowestHouseNumber] will give me the first element of the array.

To create an array with a custom lower bound , we need to use Array.CreateInstance

Array houses = Array.CreateInstance(typeof(HouseInfo), new int[] {numberOfHouses}, new int[] {lowestHouseNumber})

I was thinking you can just access it like how I access any Array of type integer as follows:

houses[houseNumber] = someHouseInfo;

But I am getting Error: CS0021: Cannot apply indexing with [] to an expression of type 'Array'

Digging more I found that the Array is a base class that doesn't implement the indexer,but when you do this for example:

int[] someArray = new int[] {4,6,6};

then you are creating a "Array Type" that is derived from Array, which implement indexer.

Is there a simple way to create an array type for that type (HouseInfo), with a custome LowerBound ?

0

There are 0 best solutions below