-1

Here is a snippet of the code that is causing the error

if(items[0] != null)
{
    equippedItem = items[0];
}

Here is a snippet of the items list:

public List<InventoryItem> items = new List<InventoryItem>();

Here is a snippet of the

public InventoryItem equippedItem;
  • 5
    An ArgumentOutOfRangeException means that the index you supplied is beyond the number of items in the list. Are you sure `items` is populated with anything? If you have population logic, can you share it? – Serlite Feb 10 '23 at 08:00
  • 1
    Does this answer your question? [Check if list is empty in C#](https://stackoverflow.com/questions/18867180/check-if-list-is-empty-in-c-sharp) – Serlite Feb 10 '23 at 08:02

2 Answers2

1

I would change this:

if(items[0] != null)
{
    equippedItem = items[0];
}

To this:

if(items.Any() && items[0] != null)
{
    equippedItem = items[0];
}

This will check if the list is initialized and has items. If it does have items, you can get the first item from the list.

And if you really want to get the first item from that list at all times, maybe use something like this:

InventoryItem equippedItem = items.FirstOrDefault();

if(equippedItem != null)
{
    // Add some cool code    
}

The FirstOrDefault gets the first item from a list. If there isn't a first item, the result will be the default value of the type (int = 0, bool = false, InventoryItem = null). You could also use First(), but that would throw an exception if there isn't a first (index 0).

I would try to avoid indexes as much as possible, because it's very sensitive for errors.

Banana828
  • 30
  • 4
  • Why use `Any` though? Rather check the `Count != 0` instead of going through Linq – derHugo Feb 10 '23 at 14:00
  • @derHugo A matter of taste? I like LINQ and I use it a lot. But if you rather use count or other methods, that is up to you. Besides, both count and Any throw exceptions when the list is NULL. – Banana828 Feb 10 '23 at 16:15
  • Was just wondering because if you know it is a list then the built-in property `Count` is way faster than using `Any` ;) we already know the list is not `null` but empty – derHugo Feb 11 '23 at 15:49
0

I actually found specifically that if you do this it works:

if (items.Count != 0)
        {
            if(items[0] != null)
            {
                equippedItem = items[0];
            }
        }