Reputation: 3268
I'm working on a small app on .NET, I need to point the same data with 2 diferent lists, I'm wondering if perhaps the memory is duplicated, for example
public class Person
{
public string name;
public int age;
....
public Person(name, age)
{
this.name = name;
this.age = age;
}
}
SortedList<string> names;
SortedList<int> ages;
Person person1 = new Person("juan",23);
names.add("juan",person1);
ages.add(23,person1);
I guess that .NET as Java will not duplicate the object Person, so it will be keeped, so if I do this:
names("juan").age = 24
Will change the object in both lists.
Is it right?
Thank you.
Upvotes: 5
Views: 352
Reputation: 73243
To test reference equality, you can always do:
bool equals = ReferenceEquals(obj1, obj2);
//in your case, obj1 = names["juan"], and obj2 = ages[23]
If reference is the same that means any change on it will be reflected on variables that reference to the same object.
In your case, yes they are just the same reference in both lists.. So if you do anything on the reference, be it on person1
, names["juan"]
or ages[23]
it will be reflected everywhere. That said, your collection should look like:
Person person1 = new Person();
SortedList<string, Person> names = new SortedList<string, Person>();
SortedList<int, Person> ages = new SortedList<int, Person>();
names.Add("juan", person1);
ages.Add(23, person1);
//names["juan"].age
//ages[23].age
//etc
Upvotes: 1
Reputation: 1063433
Because Person
is a class, you are only putting a reference into the list, so each list will have a reference to the same person. The Person
object will indeed not be duplicated, and names["juan"]
will de-reference the original object.
However! That doesn't make the code faultless:
SortedList<,>
won't like thatnames["juan"]
won't automatically update ages
; ages[24]
will failIf Person
was a struct
, then the Person
would be copied every time you assign it (but: this is not a good candidate for a struct
; don't do that)
Upvotes: 5
Reputation: 9578
Yes, This Will change the object in both lists.
if you want to provident this i suggest to overload the "=" operator (explicit )
Upvotes: 0