x


bounds checking a list?

How do I check if a value in a list valid in C#? I have a list that dynamically grows and shrinks but when the list is Empty(no values/entries in the list), I want to run alternate code.

So something like this: if(value == "ArgumentOutOfBounds") { //do This }

How do I do code that actually works in this situation?

more ▼

asked May 03 '11 at 08:49 AM

Ari Levi gravatar image

Ari Levi
173 8 9 14

(comments are locked)
10|3000 characters needed characters left

2 answers: sort oldest

Use the list's Count property.

if(index < List.Count)
{
    (Safely work with List[index])
}
more ▼

answered May 03 '11 at 08:55 AM

CHPedersen gravatar image

CHPedersen
6k 13 22 61

is there a way to do it without referring to the actual list or is that the only way. like: if(value == "ArgumentOutOfBounds") { //do This }

May 03 '11 at 09:50 AM Ari Levi

Well... sort of. It looks to me like you'd like to take some kind of action in the event that the list throws an index out of bounds exception upon access to it. The way to do that is to enclose the potentially offending code in a try-clause and catch the OutOfBounds exception. See http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx

And catch IndexOutOfRangeException in the catch-clause.

May 03 '11 at 10:42 AM CHPedersen
(comments are locked)
10|3000 characters needed characters left
 List<string> list = new List<string>();
        int amountOfItemsInList = list.Count;
        if (amountOfItemsInList == 0)
        {
            //List is empty
        }
        else
        {
            //List is not empty
        }

        int indexIWantFromList = 5;
        if (indexIWantFromList < amountOfItemsInList)
        {
            //Index found in list
        }
        else
        {
            //index not found in list
        }
more ▼

answered May 03 '11 at 08:57 AM

Maarten gravatar image

Maarten
607 2 4 12

List.Count is a property, not a method. :) Otherwise, yes.

May 03 '11 at 09:14 AM CHPedersen

Thanks, i've changed it!

May 03 '11 at 09:30 AM Maarten
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1363
x356
x77
x40

asked: May 03 '11 at 08:49 AM

Seen: 1215 times

Last Updated: May 03 '11 at 08:49 AM