19

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.

0

5 Answers 5

14

It's not an error, it's just printing out the list. The default ToString() implementation of List simply prints the name of the type.

I'm guessing you want it to work like in PHP, where you print arrays separated by commas? Try:

string.Join(", ", player.inventory);
Sign up to request clarification or add additional context in comments.

Comments

9

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));

3 Comments

I used the example you posted. It works now and I'll use this until I work out how to put this into a one line piece of code.
@Jon, Why does it need to be a one liner? In many cases i'd choose the code that's more readable and easiest to maintain. However, i will edit my answer to include a one line solution so that you can see how it's done :)
Now that you've posted the one liner, the foreach loop is easier to understand.
5

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);
}

Comments

4

print next string to console, if you want to print all items at once:

string items = string.Join(Environment.NewLine, player.inventory);

Console.WriteLine(items);

this will print each item in separate line

By default ToString() (which is called on list when you pass it to Console.WriteLine) will print the type of the list, not the contents itself. That's why you receive System.Collections.Generic.List`1[System.String]. on console screen.

Comments

2

If you want to input all the inventory items, the flowing code should work:

foreach (string inventoryItem in player.inventory)
{
     Console.WriteLine(inventoryItem);
}

the player.inventory is a collection object and cannot be input directly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.