Initializing an array on arbitrary starting index in c#

戏子无情 提交于 2019-11-27 15:14:53
expedient
James Boother

It is possible to do as you request see the code below.

// Construct an array containing ints that has a length of 10 and a lower bound of 1
Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 });

// insert 1 into position 1
lowerBoundArray.SetValue(1, 1);

//insert 2 into position 2
lowerBoundArray.SetValue(2, 2);

// IndexOutOfRangeException the lower bound of the array 
// is 1 and we are attempting to write into 0
lowerBoundArray.SetValue(1, 0);

Not simply. But you can certainly write your own class. It would have an array as a private variable, and the user would think his array starts at 1, but really it starts at zero and you're subtracting 1 from all of his array accesses.

You can write your own array class

I don't think if it's possible to modify the starting index of arrays.

I would create my own array using generics and handle it inside.

Just keep of const int named 'offset' with a value of one, and always add that to your subscripts in your code.

I don't think you can create non-zero based arrays in C#, but you could easily write a wrapper class of your own around the built in data structures.This wrapper class would hold a private instance of the array type you required; overloading the [] indexing operator is not allowed, but you can add an indexer to a class to make it behave like an indexable array, see here. The index function you write could then add (or subtract) 1, to all index's passed in.

You could then use your object as follows, and it would behave correctly:

myArrayObject[1]; //would return the zeroth element.

In VB6 you could change the array to start with 0 or 1, so I think VBScript can do the same. For C#, it's not possible but you can simply add NULL value in the first [0] and start real value at [1]. Of course, this is a little dangerous...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!