I'm building a menu where the user can add multiple strings to "the backpack", using a while loop.
Tried to store addedItem to backpackContent so that the user can add multiple strings to backpackContentny [selecting "1"] multiple times. But when trying to print the backpack content [selection "2"] it doesn't print the strings we've added, but prints this:
The backpack contains: System.Collections.Generic.List`1[System.String]
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace backpack_stackoverflow
{
internal class Program
{
static void Main(string[] args)
{
bool controllBool = true;
List<string> backpackContent = new List<string>();
while (controllBool)
{
Console.WriteLine("Welcome to the backpack.");
Console.WriteLine("[1] Add an item to backpack");
Console.WriteLine("[2] Print backpack content");
Console.WriteLine("[3] Clear backpack content");
Console.WriteLine("[4] Exit");
string menuSelection = Console.ReadLine();
switch (menuSelection)
{
case "1":
Console.WriteLine("Add something to the backpack: ");
string addedItem = Console.ReadLine();
backpackContent.Add(addedItem);
Console.WriteLine("You have added a " + addedItem + " to the backpack!");
break;
case "2":
if (menuSelection == "")
{
Console.WriteLine("The backpack is empty. Add something by pressing menu selection 1.");
}
else
{
Console.WriteLine("The backpack contains: " + backpackContent + "."); }
break;
case "3":
Console.WriteLine("You have cleared the backpack! Add something by pressing menu selection 1.");
break;
case "4":
controllBool = false;
break;
default:
Console.WriteLine("It seems you have made an invalid selection. Please make an selection between 1-4.");
break;
}
}
}
}
}
"The backpack contains: " + backpackContent + "."it takes backpackContent and calls "ToString()" on it. But ToString on a list doesn't enumerate the items in the list as you are expecting. It calls the default ToString on all objects, which outputs the type (which is what you're seeing). You'll need to actually loop through the list and write out each item.List<string>has no meaningful default string representation. The linked duplicate shows how to usestring.Jointo combine the list into a single string."The backpack contains: " + string.Join(", ", backpackContent) + "."