C# List of class instances

I am not new to programming but I am very new to C#. I am trying to populate a list with instances of a class.

I would expect the following piece of code to display numbers 0 to 9 in the console but instead it repeats 9 ten times. Clearly I am doing something wrong.

I am suspecting that adding "a" to the list simply adds a reference to "a", and not a new instance of class1. I am not sure what I should be adding though. What would be the correct syntax to add a new instance of class1 to the list?

Thanks in advance for any answer!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<class1> iList = new List<class1>();
            class1 a = new class1();

            for (int i = 0; i < 10; i++)
            {

                iList.Add(a);
                iList[i].var1 = i;
            }
            for (int i = 0; i < iList.Count; i++)
            {
                System.Console.Write("var1 of " + i + ": " + iList[i].var1 + "\r\n");
            }
            Console.ReadLine();
        }
    }

    class class1
    {
        public int var1;
    }
}

Upvotes: 1

Views: 6928

Answers (2)

Lucas Rodriguez
Lucas Rodriguez

Reputation: 1203

You are adding the same object over and over again, and that's it's causing that all ten items are pointing to the same object.

When you add an object to a list, you are not creating a new object. You are adding a reference to the object you are adding. In this example, you are adding the same reference 10 times. Thus, every time you access the var1 property, you are re writing the same value.

Then, when you are looping over the list (that will contain 10 references) all this references are pointing to the same object.

The instance of class1 should be in the loop:

for (int i = 0; i < 10; i++)
{
    class1 a = new class1();
    iList.Add(a);
    iList[i].var1 = i;
}

Upvotes: 9

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

Which programming language you are familiar to? In normal popular language objects from classes are referent data types. If you add twice the same instance in a list, changing a field in that instance will reflect both elements in the list.

In your particular case you are adding only one instance 10 times. On the last iteration you do change the value of the field to 9 which reflects all items in the array pointing to that instance.

If you want to achieve the desired behavior, you need to add new instances of the class. E.g. to create it in the loop, not outside it.

Upvotes: 1

Related Questions