Home » excel » c# – Non-zero based multidimensional arrays

c# – Non-zero based multidimensional arrays

Posted by: admin March 9, 2020 Leave a comment


I am extracting cells out of a spreadsheet using the Interopt.Excel API. When I call:

object[,] rangeValues = (object[,])range.get_Value(XlRangeValueDataType.xlRangeValueDefault);

And set a breakpoint and inspect rangeValues, I see elements starting at [1,1] “foo”, [1,2] “bar”, etc.

However, if I do string[,] test = new string[2, 2] { { "one", "two" }, { "three", "four" } };

The elements start at [0,0]. How does the Excel API construct a multidimensional array w/ empty elements? I tried adding null but you still have an [0,0] entry. Their object doesn’t show that.

How to&Answers:

The CLR supports non-zero based arrays. They are confusing and to be avoided. I believe, the COM interop marshaller can create them.


Common Language Specification (CLS) compliance requires that all
arrays be zero-based. This allows a method written in C# to create an
array and pass the array’s reference to code written in another
language such as Visual Basic®. In addition, since zero-based arrays
are by far the most common, Microsoft has spent a lot of time
optimizing their performance. However, the CLR does support
non-zero-based arrays but they are discouraged. For those of you who
do not care about performance and cross-language portability, I will
demonstrate how to create and use non-zero-based arrays later in this

This is the first time I have seen one in real-world code.

Apparently, multi-dimensional arrays have the same type no matter whether they are zero-based or not. Single-dimensional ones have a different type. Makes sense because if they had the same type the JIT would always have to produce slow code for the general case.

enter image description here