Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++

The code: int[,] intMatrix2D1 = (int[,])Array.CreateInstance(typeof(int), new int[] { 10, 10 }, new int[] { 1, 1 }); is able to make a 2d matrix with a lower bounds of 1. However, the same function can only make 0-based vectors. I've tried to look up ways to do this and the closest I've gotten is a cryptic note on the Type.MakeArrayType method page that states:

The common language runtime makes a distinction between vectors (that is, one-dimensional arrays that are always zero-based) and multidimensional arrays. A vector, which always has only one dimension, is not the same as a multidimensional array that happens to have only one dimension. This method overload can only be used to create vector types, and it is the only way to create a vector type. Use the MakeArrayType(Int32) method overload to create multidimensional array types.

Simply put, is there a fairly simple way to create a 1 dimensional array that has a lower bounds of 1?

Thank you,
~Scott
Posted
Comments
Scottingham 3-Aug-11 14:06pm    
I should also add that this problem is due to the fact that a very large amount of very complex code written in R was converted to c#. R uses 1 based arrays.

Furthermore, attempting to do the following: int[] intVector1 = (int[])Array.CreateInstance(typeof(int), new int[] {10},new int[] {1}); leads to the error: "Unable to cast object of type 'System.Int32[*]' to type 'System.Int32[]'."

1 solution

This is a fairly simple way: System.Array.CreateInstance with lower bound. You can specify lower bounds even with the array rank more then 1, see System.Array.CreateInstance(Type, Int32[], Int32[]).

If you do this, you have to use GetLowerBound, SetValue, GetValue, etc. See the usage sample:
http://msdn.microsoft.com/en-us/library/system.array.getlowerbound.aspx[^].

To my taste, it does not worth bothering, but you should decide by yourself.

If you asked about my preferences, I would always work with zero-based indexing — at lower level.

If I had a requirement to implement arbitrary indexing bases, no matter what the rank of array data is, I would create a wrapper of the array data on semantic level. In this wrapper, I would create indexed property ("this") with required types of indices. I would offset the value of integer index in the property getter/setter to achieve the effect of non-zero-based indexing. Internally, indexing would remain zero-based.

You can easily do the same. Again, decide by yourself.

—SA
 
Share this answer
 
v2
Comments
Abhinav S 3-Aug-11 14:16pm    
Good answer. 5.
Sergey Alexandrovich Kryukov 3-Aug-11 14:36pm    
Thank you, Abhinav.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900