Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List overwriting data on all positions [duplicate]

Tags:

c#

list

I created a class with 3 fields:

class Gente
    {
        int _ID;
        string _nome, _sexo;


        public Gente()
        {
            _ID = 0;
            _nome = "";
            _sexo = "";
        }

        public int ID
        {
            set { _ID = value; }
            get { return _ID; }
        }

        public string Nome
        {
            set { _nome = value; }
            get { return _nome; }
        }

        public string Sexo
        {
            set { _sexo = value; }
            get { return _sexo; }
        }
    }

Then I declared a List from that class and an object from that class so that I can be able to add to the List.

List<Gente> Alunos = new List<Gente>();        

        Gente professor = new Gente();

The first time I do the Alunos.Add(professor); to the list it correctly sends the information to the 0 position.

But when I do it second time it overwrites everything on position 0 with the new data besides adding the new data to a new position, 1.

like image 255
elvispt Avatar asked Apr 30 '10 12:04

elvispt


1 Answers

What does your code to add the two objects to the list look like? My guess is:

Gente professor = new Gente();
professor.Nome = "Fu";
Alunos.Add(professor);

professor.Nome = "Bar";
Alunos.Add(professor);

Which is incorrect. When you add reference types to a list, you're only adding a reference to the original object. In this case you're adding two references to the same object twice.

Therefore, when you modify the second object...you're also modifying the first.

A simple one-liner fix would be to re-initialize professor before its second use:

Gente professor = new Gente();
professor.Nome = "Fu";
Alunos.Add(professor);

professor = new Gente();
professor.Nome = "Bar";
Alunos.Add(professor);
like image 135
Justin Niessner Avatar answered Nov 14 '22 23:11

Justin Niessner