0

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 ?

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
Ghassan Karwchan
  • 3,355
  • 7
  • 37
  • 65
  • No, you can't do this with `new []` and for good reason! Could you imagine if any time you went to use the array you first had to check for lower bounds other than 0? It would be nearly unusable. – David L Sep 07 '22 at 22:24
  • If you want to access objects in a collection using a key then use `Dictionary`. – Valuator Sep 07 '22 at 22:25
  • Since you have a `System.Array` you need to use `houses.SetValue(someHouseInfo, houseNumber);` to set values (and `(HouseInfo)houses.GetValue(houseNumber);` to retrieve them) – UnholySheep Sep 07 '22 at 22:29
  • You need to use `houses.SetValue(someHouseInfo, houseNumber);`. Also, each successive array element has its index incremented by `1`, so unless your house numbers differ by `1`, too (instead of `5` or `10` or whatever), then this will be a very sparsely-populated and inefficient array. – Lance U. Matthews Sep 07 '22 at 22:31
  • 1
    Or you could use a normal array and mply subtract 1000 from the house number – pm100 Sep 07 '22 at 22:39

0 Answers0