© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
62 replies
Ossie

Index was out of range. How to check if list has items without triggering this error?

Hello, I have a list, with a list inside.
 List<List<dynamic>> characterData
 List<List<dynamic>> characterData


This is because I wan't to have 3 possible lists, with a list inside. However there isn't always 3 lists present. Sometimes it might only be 1 or 2 lists that are filled, and the last one is empty. My problem occurs when trying to check if the List has any value. This works fine if none of the lists have any value, by checking if
characterData.Count > 0
characterData.Count > 0
. However when this is not the case, I try to check if a value inside the list is NullOrEmpty, however this is causin the error
Index was out of range
Index was out of range
. Which makes sense because the list doesn't exist, but how would I then check if the list itself exists inside the the other list? I hope this makes any sense, I will post a snippet.

I would wanna check if characterData[i] exists, without getting an index error.

 List<List<dynamic>> characterData // This get its value from another place, not important

for (int i = 0; i <= 2; i++)
{
  if (characterData.Count > 0)
  {
    if (!string.IsNullOrEmpty(characterData[i][0].ToString())) // This give me a error, so how do I check if the list has any values, I'm just checking the first value as it seemed logically to me
    {
      // Rest of my code
    }
  }
}
 List<List<dynamic>> characterData // This get its value from another place, not important

for (int i = 0; i <= 2; i++)
{
  if (characterData.Count > 0)
  {
    if (!string.IsNullOrEmpty(characterData[i][0].ToString())) // This give me a error, so how do I check if the list has any values, I'm just checking the first value as it seemed logically to me
    {
      // Rest of my code
    }
  }
}


Thanks,
Ossie
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

Weird error to do with index out of range
C#CC# / help
2y ago
✅ how to know the index of repeated items in list ?
C#CC# / help
4y ago
❔ index out of range or non-negative
C#CC# / help
3y ago
System.IndexOutOfRangeException: "The index was out of range of the array." c# ReadWriteMemory
C#CC# / help
3y ago