I decided to make a small little console based RPG to learn classes. I have a basic game going, but I have a problem. I'm trying to display the players inventory from the Player class in another class.
I'm using a List to hold the players inventory.
public List<string> inventory = new List<string>();
This is in the Players class file.
Then in the Shop Class, I'm doing;
Player player = new Player();
To make a new object to access the player class. Then to add something to the List in the shop, I'm doing;
player.inventory.Add("Axe");
But if I make the player.inventory();
print out in the console, I get the wrong result:
System.Collections.Generic.List`1[System.String]
How can I fix this? I should get Axe
instead.
System.Collections.Generic ClassesIt stores key/value pairs and provides functionality similar to that found in the non-generic Hashtable class. It is a dynamic array that provides functionality similar to that found in the non-generic ArrayList class.
The System. Collections namespace contains the non-generic collection types and System. Collections. Generic namespace includes generic collection types.
Immutable namespace offers generic collection types you can use.
You require a foreach
loop to iterate each and every member of your list. You can't just print the list as a whole.
You need something like:
foreach(var i in Player.Inventory)
{
Console.WriteLine(i);
}
You're trying to print a list object and not the values contained within the list, you need something like: -
foreach(var i in player.Inventory)
{
Console.WriteLine(i);
}
Edit* As per comments
Console.Write(string.Join(System.Environment.NewLine, player.Inventory));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With