Retrieving last index value in an ArrayList

I want to populate an int variable with the last index of an ArrayList. I haven't yet found a property of ArrayList that will do that for me and I'm wondering if I'm missing something. Right now I am doing it this way:

int theLastIndex = theArrayList.Count - 1

But I'm wondering if there is a more elegant way.

This is in C#, by the way.

Thanks in advance.



Answer this question

Retrieving last index value in an ArrayList

  • martok

    Yes, that is correct.

    Normally, though, you should avoid basing too much logic around the last index of the array/ArrayList, and instead just use the size. Then instead of looping while, say, i <= lastIndex, you loop while i < arrayList.Count. This is something that I didn't do when I was first learning java, so I frequently had off-by-one errors, etc.

    I don't know the specific situation you're in, though, so disregard that info if you already knew it or it doesn't apply.

  • HMote

    A teeny weeny bit more elegent, if you're into that sort of thing:

    int lastIndex = theArrayList.Count++;



  • iSerg

    this would be the way of getting the last index of the array

  • Aleniko29139

    Sorry, but that won't work at all. If that even could compile, it would set the lastIndex value to theArrayList.Count and then increment theArrayList.Count. However, Count is read-only, since it doesn't make sense to increase the number of items without actually adding an item.

  • Flavia Lemes

    Hah! You're right. I plead pre-coffee!

  • Retrieving last index value in an ArrayList