Maybe I'm just not seeing why, but I am getting an index out of range exception. I am adding items to an array(assignment requirement, I know I should be using a list or SQL server directly to store this information if this were a normal situation) through my addItem method, which takes an inventory item as an argument.
public void addItem(Inventory item)
{
if (inventory.Length >= capacity)
{
capacity *= 2;
Inventory[] temp = new Inventory[capacity];
int i = 0;
foreach (var inv in inventory)
{
temp[i] = inventory[i];
i++;
}
inventory = temp;
}
inventory[size] = item;
++size;
return;
}
While trying to remove the item with my removeItem method, which also takes an inventory item as an argument, I'm getting an index out of range exception. I'm not seeing why, as when I remove the element from my inventory array, I should be shifting all elements over.
public void removeItem(Inventory item)
{
int index = Array.IndexOf(inventory, item);
for (int i = index; i < size; i++)
{
inventory[i] = inventory[i + 1];
}
}
I know it's just going to end up being an off by one error that I'm not seeing how to fix and kick myself for it.
edit: these are the initial values of size, capacity, and the array.
Inventory[] inventory = new Inventory[10];
int capacity = 10;
int size = 0;
edit2: i and index are sitting at -1, which I'm unclear on.
int index = Array.IndexOf(inventory, item);
This should be grabbing the index of an inventory item from my array, however is returning -1 to me as if it does not exist. In my winform, I have each text field feeding into an item to be removed here:
private void btnRemoveItem_Click(object sender, EventArgs e)
{
int value;
double filler;
if (int.TryParse(textBoxSku.Text, out value) && int.TryParse(textBoxQuantity.Text, out value) && double.TryParse(textBoxPrice.Text, out filler))
{
//parsing successful
Inventory item = new Inventory(int.Parse(textBoxSku.Text), int.Parse(textBoxQuantity.Text), textBoxDescription.Text, double.Parse(textBoxPrice.Text));
app.removeItem(item);
}