Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting System.Collections.Generic.List`1[System.String] instead of the list's contents? [duplicate]

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.

like image 633
Jon Avatar asked Apr 19 '13 13:04

Jon


People also ask

What is using System collections generic?

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.

Which namespace contains all generic based collection classes?

The System. Collections namespace contains the non-generic collection types and System. Collections. Generic namespace includes generic collection types.

What is the namespace used for generic collections?

Immutable namespace offers generic collection types you can use.


2 Answers

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);
}
like image 56
Gopesh Sharma Avatar answered Sep 18 '22 09:09

Gopesh Sharma


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));
like image 38
DGibbs Avatar answered Sep 18 '22 09:09

DGibbs