Vector of objects (Doubt) - C #

1

In the next 2 cases I find it hard to understand the execution flow. Look at the Line marked with %%%%%%%%%%%%%% is the line where my question is presented, Initially I put that line out of for but I got a output in which only the last element of the vector repeated twice was returned. Now, although this is resolved, I could not understand why ...

This is my logic, correct me where I got lost or I was wrong, when line %%%% is out of for , I start entering the number 2 to generate a vector of 2, well once this is done, the for starts % requesting me the data A.id I continue with A.nom ends the first round with lista[cont]=A , OKey, starts the second, repeats everything again, only this time, the values of A are reassigned, so when it reaches the end lista[cont]=A the second element ( lista[1] ) has new values, and then, why does lista[0] disappear taking the same value as lista[1] ?

Code:

int public main()
{
    Console.WriteLine("ingrese cantidad de objetos");
    int i =int.Parse( Console.ReadLine());
    servivo[] lista = new servivo[i] ;
    for (int cont = 0; cont < i; cont++)
    {
        servivo A = new servivo(); %%%%%%%%%%%%%%%%%%%%%%

        Console.WriteLine("ing id");
        A.id = Console.ReadLine();
        Console.WriteLine("ing nom");
        A.nom = Console.ReadLine();

        lista[cont] = A;

    }
    Console.WriteLine("Lista de objetos");

    for (int cont = 0; cont < i; cont++)
    {
        Console.WriteLine(lista[cont].id);
        Console.WriteLine(lista[cont].nom);

    }
    Console.ReadKey();
}

class servivo
{
    public string id;
    public string nom;
     public void respiro()
    { Console.WriteLine("puedo respirar"); }
}

EXAMPLE 2

int[] lista = new int[2];
        int var;

        for (int cont = 0; cont < 2; cont++)
        {
            Console.WriteLine("ingrese valor para var");
            var=int.Parse(Console.ReadLine());

            lista[cont] = var;
        }

        for (int cont = 0; cont < 2; cont++)
        {
            Console.WriteLine(lista[cont]);
        }

            Console.ReadKey();
    
asked by Shiki 17.05.2017 в 07:32
source

1 answer

2

Good morning, if you take the line servivo A = new servivo(); out of the loop what you are assigning each iteration to the array lista[] is the same reference to the same object, that's why lista[0] and lista[1] have the same values. It is necessary to instance a new object 'servivo' in each iteration (that is, within the loop) so that each element assigned to 'list' points to a different reference. You can see more information about types by value and by reference in Types (Reference C #)

    
answered by 17.05.2017 / 08:54
source