tags:

views:

29

answers:

1

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.

+6  A: 

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);
Justin Niessner
You should add that inserting `professor = new Gente();` on line 4 fixes the problem.
Jens
OK Thanks mate. It worked. =)
elvispt