views:

2870

answers:

8

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

A: 

You can write your own array class

Dested
A: 

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...

Daok
The properties require the array to start in 1, so this wouldn't work
Juan Manuel
+1  A: 

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.

Aaron
Yeah, you can always do anything yourself... the question is if it can be done with c# syntax
Juan Manuel
+4  A: 

You can use Array.CreateInstance.

See Array Types in .NET

expedient
I really wanted to know if it was syntactically possible, but this is a great solution
Juan Manuel
A: 

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.

snomag
A: 

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

Joel Coehoorn
A: 

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.
xan
+4  A: 

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);
James Boother