Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicated Memory on .NET using two lists

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.

like image 794
Manjar Avatar asked Jan 24 '13 10:01

Manjar


1 Answers

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:

  • there might be more than one person aged 23; SortedList<,> won't like that
  • changing the age via names["juan"] won't automatically update ages; ages[24] will fail

If 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)

like image 116
Marc Gravell Avatar answered Sep 21 '22 18:09

Marc Gravell