C # - Reference to objects and vectors

2

I have a problem where by installing a new object and then this object to be part of a vector of objects of this same type, but when I request a return data of 2 different indexes of the vector, it returns the same information.

Note: vectermi is a method which expands the size of the vector of objects because when you initialize it you have to indicate the amount of elements that it will contain

       if (opcion == "1")
        {
            terminal x = new terminal();

            Console.WriteLine("Ingrese nombre de la terminal");
            x.ntermi = Console.ReadLine();
            Console.WriteLine("Ingrese nombre de la ciudad");

            x.ciudad = Console.ReadLine();
            Console.WriteLine("La terminal fue dada de alta correctamente");
            Ltermi = vectermi(Ltermi, x);

            Console.WriteLine(Ltermi[0].ntermi);
            Console.WriteLine(Ltermi[Ltermi.Length-1].ntermi);

            Console.ReadKey();
            menurecorridos();

        }

// VECTERMI METHOD

public static terminal[] vectermi(terminal[]z,terminal x)
    {
        if (z.Length == 1)
        {
            z[0] = x;
            return z;
        }


            terminal[] vec = new terminal[z.Length + 1];
            for (int cont = 0; cont < z.Length; cont++)
            {
                vec[cont] = z[cont];
            }
            vec[vec.Length - 1] = x;
            return vec;

    }

The terminal class has 2 fields: ntermi (which is terminal name) and ciudad . When entering the if instancio a new terminal object, by entering the keyboard filled those fields, (let's assume that the data in ntermi=T1 ciudad= blabla ), then repeat the entry to enter another data more than another new terminal object (This time is ntermi = T2 and ciudad= vlavla .

Then I ask you as you see in the code, the element of the beginning and the end, ie terminal[0].ntermi and terminal[terminal.Lenght-1].ntermi but only gives me output T2 T2 when it would have to be T1 and T2

    
asked by Shiki 29.06.2017 в 10:39
source

1 answer

2

The problem is here:

if (z.Length == 1)
{
    z[0] = x;
    return z;
}

Since you start with an array of size 1, whenever you call this function, it always returns the same array with the same size.

The solution is easy. Initialize your Ltermi array with size 0:

terminal[] Ltermi = new terminal[0];

And remove from the method vectermi the code that I put above that checks the size of the array.

    
answered by 29.06.2017 / 11:11
source