Reputation: 147
I created a 20x20 multi-dimensional array that is treated as a map.
private LinkedList<Item>[,] m_map = new LinkedList<Item>[width, height];
Each cell is a linked list of type Item. Items of weapons, armor, etc. can be dropped into each cell.
I have the following class hierarchy:
class Item
{
public string name;
}
class Weapon : Item
{
public int damage;
}
class Armor : Item
{
public int ar;
public int weight;
}
I was a little surprised, and would like to be educated on this part. Since the type is LinkedList< Item >, I didn't think I could store an Armor type and retrieve it. This is how I'm retrieving a specific item type:
/// <summary>
/// Gets a list of weapons at the given coordinates.
/// </summary>
/// <param name="x">The map's horizontal position.</param>
/// <param name="y">The map's vertical position.</param>
/// <returns>Returns a list of weapons at the given coordinates.</returns>
public List<Weapon> GetWeapons(int x, int y)
{
List<Weapon> weapons = new List<Weapon>();
foreach (Item item in m_map[x, y])
{
if (item is Weapon)
{
weapons.Add(item as Weapon);
}
}
return weapons;
}
Item contains less fields than Armor, so I figured the type LinkedList< Item > would be smaller than Armor. However, it seems to have enough room to save an Armor object to it. I'm able to retrieve Armor's data.
When you store derived types to a link list with its base type, does the compiler make enough memory for its derived types? I'm surprised I could retrieve an Armor type and still get its derived data (ar, weight).
Can someone explain why this works? Thank you.
Upvotes: 0
Views: 262
Reputation: 82504
As Cody Gray wrote in his comment, the LinkedList stores references, not values.
A simplified explanation of reference is that it's an address to a location in the memory where the actual value resides.
Since you only store the reference, a list of 100 Items consumes just the same amount of memory as a list of 100 Weapons or Armors.
However, this is only a part of the reason why you can store derived class instances in a list of parent class - The other part is a basic OOP concept called Polymorphism - The fact that an Armor
or a Weapon
is in fact a type of Item
enables you to store each of them inside any storngly typed collection of type Item
, because you can use a reference of type Item
to point to an instance of Armor
or Weapon
.
To answer your comment to Cody - No. A collection stores whatever you decide it will store. If you would declare a list of int
, for example, it would store actual values, since int
is a value type.
You might want to read up on value types vs reference types.
The main difference is that a value type variable directly contain values, while reference type variables contains a "pointer" to where the actual values are stored.
Upvotes: 1