0
List<string[]> parent = new List<string[]>();
string[] child = new string[2];
bool isRunning = true;

while (isRunning)
{
            
    Console.Clear();
    Console.WriteLine("1: Add to Array with 2 elements");
    Console.WriteLine("2: Show all elements");
    
    Console.WriteLine("3: Close program");

    string awnser = Console.ReadLine();

    switch (awnser)
    {
        case "1":
            Console.WriteLine("Element number 1:");
            child[0] = Console.ReadLine();
            Console.WriteLine("Element number 2:");
            child[1] = Console.ReadLine();

            parent.Add(child);
            break;

this would cause the list to have the last array value in all list values

List<string[]> parent = new List<string[]>();
        
bool isRunning = true;

while (isRunning)
{
    Console.Clear();
    Console.WriteLine("1: Add to Array with 2 elements");
    Console.WriteLine("2: Show all elements");
    Console.WriteLine("3: Close program");

    string awnser = Console.ReadLine();

    switch (awnser)
    {
        case "1":
            string[] child = new string[2];
            Console.WriteLine("Element number 1:");
            child[0] = Console.ReadLine();
            Console.WriteLine("Element number 2:");
            child[1] = Console.ReadLine();

            parent.Add(child);
            break;

This would add the new values to the list without replacing it. What is so special about arrays in a list.

I don't know why putting it in the while-loop causes the difference, could someone help me understand why?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
Lillan
  • 1
  • 1
  • This is reference-types semantics. In the first code you use the same `array`-object on every iteration and just modify its content. In the second code you create completely independent arrays. – MakePeaceGreatAgain Mar 09 '23 at 11:54
  • I think I understand, so in the first code I add the change of the array to the list and the change applies to all arrays in the list, while in the second code I add a new array to the list – Lillan Mar 09 '23 at 12:09
  • not entirely... in the first case there is only one single array, not multiple ones. That one array is just re-used on every iteration. – MakePeaceGreatAgain Mar 09 '23 at 12:14
  • so in the first code I just add another place the array exists in the list while I modify its content – Lillan Mar 09 '23 at 12:23

0 Answers0