This demo class to explain the question
public class SomeClass
{
public string Name { get; set; }
public int Age { get; set; }
}
While developing something equals to the sample code I included in this question I got the following thought:
Since classes are reference type, and if I assign multiple instances to the same class object using loop and store these objects in an list, isn’t that enough to ruin each object and make it equals to last instance assigned to it?
Here’s some sample implementation for the confusion
List<SomeClass> lst = new List<SomeClass>();
SomeClass someClassObj = null;
for (int i = 0; i < 3; i++)
{
someClassObj = new SomeClass();
someClassObj.Name = "Name " + i.ToString();
someClassObj.Age = i;
lst.Add(someClassObj);
}
after testing it does not wokred the way I though it would, anyway that what i want
anyone help to clear this confusion.
Every time you do
someClassObj = new SomeClass();a new memory piece is created in heap and it’s address is assigned to
someClassObjwhich means in your list there is not actually only single address which you are adding again and again but a new address and that’s why when you will compare the object they won’t be same because they have a different addressinitially
SomeClass someClassObj = null;your object is pointing to nothing. when you create a new instance usingnew ()your object starts pointing to newly allocated memory’s address. So, inside loop, every instance is assigned new address and that address is stored inSomeClasswhich is same pointer/reference. When you add item in the list, it actually adds the address/reference of item that is currently pointed bySomeClass