Add and remove
- Game Development course
- Intermediate
- Lesson 76/83
- 4 min
Learn methods to add and remove items from the list.
Adding an Item to the Inventory
The Add method of a List<T> collection appends a new element to the list. You can use this method to store new Item objects in the inventory. Grouping the operation inside a separate method keeps inventory management organized.
items.Add(item);Removing an Item from the Inventory
The Remove method removes the specified object from the collection if it is found in the list. It returns a bool value indicating whether the object was found and removed. RemoveAt can be used to remove an element at a specified index.
bool removed = items.Remove(item);Practice Write Add and Remove Methods
Assume that the InventoryManager class contains a list of Item objects. The AddItem method should append the received object to the list. The RemoveItem method should attempt to remove the received object from the list.
Starter code
using System.Collections.Generic;
public class InventoryManager
{
private List<Item> inventory = new List<Item>();
}Sample solution
using System.Collections.Generic;
public class InventoryManager
{
private List<Item> inventory = new List<Item>();
public void AddItem(Item item)
{
inventory.Add(item);
}
public void RemoveItem(Item item)
{
inventory.Remove(item);
}
}Expected output
Ekleme ve çıkarma metotları hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is called to append an Item object to the list?
- Sort()
- Add() Correct answer
- RemoveAt()
- Clear()
Explanation: The Add method appends a new element to the collection.
2 Removing an Object from a List
Bir listedeki belirli Item nesnesini kaldırmak için ____ metodu kullanılır.
Bir listedeki belirli Item nesnesini kaldırmak için Remove metodu kullanılır.
Explanation: The Remove method attempts to remove the specified object from the list.
3 Match List Methods
| Term | Meaning |
|---|---|
Add(item) |
Appends new object to collection |
Remove(item) |
Removes specified object from collection |
RemoveAt(index) |
Removes element at given index |
Clear() |
Removes all elements from collection |