Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array on arbitrary starting index in c#

Is it possible in c# to initialize an array in, for example, subindex 1?

I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.

As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.

But, I was wondering if it was possible to create a new non-zero based array

like image 840
juan Avatar asked Sep 17 '08 13:09

juan


People also ask

What is the starting index of an array in C?

Arrays in C are indexed starting at 0, as opposed to starting at 1. The first element of the array above is point[0]. The index to the last value in the array is the array size minus one.

Does C initialize arrays to 0?

Initialize Arrays in C/C++ c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

What is starting index of array in C with example?

An array arr[i] is interpreted as *(arr+i). Here, arr denotes the address of the first array element or the 0 index element. So *(arr+i) means the element at i distance from the first element of the array. So array index starts from 0 as initially i is 0 which means the first element of the array.


1 Answers

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);
like image 194
James Boother Avatar answered Oct 21 '22 05:10

James Boother