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 someClassObj
which 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 address
initially
SomeClass someClassObj = null;
your object is pointing to nothing. when you create a new instance using new ()
your object starts pointing to newly allocated memory's address. So, inside loop, every instance is assigned new address and that address is stored in SomeClass
which is same pointer/reference. When you add item in the list, it actually adds the address/reference of item that is currently pointed by SomeClass
What you are actually doing is assigning a new reference to someClassObj
on each iteration, and then adding a copy of this reference to your list. You are not adding a reference to someClassObj
to your list. The Add
method would need to take a ref
parameter in order for it to be a reference to someClassObj
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.