- Home /
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?
Answer by CHPedersen · May 03, 2011 at 08:55 AM
Use the list's Count property.
if(index < List.Count)
{
(Safely work with List[index])
}
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 }
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.
Answer by Maarten · May 03, 2011 at 08:57 AM
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
}
List.Count is a property, not a method. :) Otherwise, yes.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Array to create a list of objects in the scene? 1 Answer
How to see what element is the current one 2 Answers
Get size of a vector3 array c# 1 Answer
Generic List.Count always gives 0 2 Answers