I created a list that stores objects from another class. The objects stored in my list each have a name and an integer. I want to know if I can iterate through my list and display the name of each object. If I change the type of i to VAR or Dynamic it says its out of range.
public List<InventoryHandling> Inventory = new List<InventoryHandling>();
public void inventorySelect()
{
Inventory[0] = new InventoryHandling("Potion", 4);
foreach(int i in Inventory)
{
Console.WriteLine(Inventory[i].Name);
}
}
To start, this line is wrong:
Inventory[0] = new InventoryHandling("Potion", 4);
The problem is the [0]
index refers to the first item in the list, but (presumably) at this point the list doesn't have any space yet. The position at index [0]
doesn't exist, and C# does not allow you to append to a list by assigning to the next index. Instead, when you want to add new items to a list, you should call it's .Add()
method:
Inventory.Add(new InventoryHandling("Potion", 4));
Now we have a list with some content, we can talk about how to iterate it. And just like appending, you don't use indexes with a foreach
loop:
foreach(InventoryHandling ih in Inventory)
{
Console.WriteLine(ih.Name);
}
If you really want to use indexes, you can do it with a for
loop:
for(int i = 0; i < Inventory.Length; i++)
{
Console.WriteLine(Inventory[i].Name);
}