0

I'm learning C# and am from a Java + Python + D background. I'm accustomed to iterating over an array from zero to its upper bound, through code such as the following (in Java):

for(int i = 0; i < array.length; i++)

But C#, for multidimensional arrays, I can't get the length of an individual dimension-- .Length on a multidimensional array gets the total number of available elements. Jagged arrays might be an exception, but they aren't what I'm working with. To get a specific dimension, I've had to use .GetUpperBound(...) , which returns the length of the array minus one.

Before I jump to any conclusions, is there a reason for it to be doing this, and cutting against a trend in C-style programming languages stretching back to at least 1972? Is there an easy way to get that value other than .GetUpperBound(...) - 1? It feels very messy to me.

Thank you!

Michael Macha
  • 1,729
  • 1
  • 16
  • 25
  • Do you have a comparable example of accessing a *multidimensional* array in Java? – Damien_The_Unbeliever Feb 09 '18 at 08:09
  • I can see some overlap, but that does not address the full scope of my question-- is it possible to quickly get the length of a dimension? – Michael Macha Feb 09 '18 at 08:10
  • 1
    I'm not sure I understand the question but can this help? https://stackoverflow.com/questions/2893297/iterate-multi-dimensional-array-with-nested-foreach-statement – Drag and Drop Feb 09 '18 at 08:12
  • @Damien_The_Unbeliever It's more or less the same; in Java, all arrays may be jagged arrays. Therefore, it would be something like array.length for the first dimension, array[0].length for the second, array[0][0].length for the third, etc. – Michael Macha Feb 09 '18 at 08:12
  • @DragandDrop That looks like what I'm looking for, thank you! Could you write it as an answer, instead of a comment, so that I can accept it? – Michael Macha Feb 09 '18 at 08:14
  • If this is what you are looking for a simple duplicate flag will be good. Duplicate are not a bad things. Asking the same question multiple time with new word will help people finding it in the future. – Drag and Drop Feb 09 '18 at 08:16
  • https://stackoverflow.com/questions/17358139/getupperbound-and-getlowerbound-function-for-array/17358481#17358481 – Dmitry Bychenko Feb 09 '18 at 08:16

1 Answers1

1

for multidimensional arrays, I can't get the length of an individual dimension-- .Length on a multidimensional array gets the total number of available elements

That makes sense since multi-dimensional arrays are actually just a contiguous block of memory. Returning Length as the actual total length of the array seems to make sense.

GetUpperBound and GetLowerBound are convenient if you want to know the actual dimensions of that array, or know if the array starts at 1 instead of 0 for example. In that case iterating over items 0..Length-1 doesn't cut it.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325