-1
List<int> MyList = new List<int>();
MyList.Add(1);
MyList.Add(2);
MyList.Add(3);
MyList.Add(4);
foreach(int item in MyList){
    System.Console.WriteLine(MyList);
}

This is what my code shows :

System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
Patrick W
  • 1,485
  • 4
  • 19
  • 27
Sebi Dragu
  • 11
  • 3
  • Possible duplicate of https://stackoverflow.com/questions/759133/how-to-display-list-items-on-console-window-in-c-sharp – Aviv Shai Jun 11 '19 at 04:03
  • Just print the number: `System.Console.WriteLine(item);` – RoadRunner Jun 11 '19 at 04:05
  • you had a loop for each 'item' in the list so you need to work on item, not 'MyList'. print item instead of 'MyList' – fahime Jun 11 '19 at 04:36
  • 2
    Possible duplicate of [How to display list items on console window in C#](https://stackoverflow.com/questions/759133/how-to-display-list-items-on-console-window-in-c-sharp) – Hargo Jun 11 '19 at 05:21
  • you are using foreach for display list objects but you trying to write list object.. change System.Console.WriteLine(MyList); to System.Console.WriteLine(item); – Mert Akkanat Jun 11 '19 at 06:07

2 Answers2

0

When you ToString an object (which is what Console.WriteLine does), and it hasn't overridden ToString() it writes the name of the class. However, you can just use item which looks like a simple mistake

var myList = new List<int> { 1, 2, 3, 4 };

foreach (var item in myList)
   System.Console.WriteLine(item);

// or, you can get fancy with string.Join

Console.WriteLine(string.Join(", ", myList));
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

You need change MyList to item to show each item in MyList variable.

foreach(int item in MyList){
    System.Console.WriteLine(item);
    }
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62