Doubt C #: print items List

1

Good I created the following List, and added several elements as I show next:

List<Persona> personas = new List<Persona>();

personas.Add(new Persona("12345678C", "Juan Francisco Cabello"));
personas.Add(new Persona("26810168B", "Jesus Romero Gonzalez"));
personas.Add(new Persona("32167678V", "Guillermo Barcia"));

for (int i = 0; i < personas.Count; i++)
{
    Console.WriteLine("INTRODUCIDO: " + personas[i].toString());
    sw.WriteLine(personas[i].toString());
    sw.WriteLine();
}

The problem is that the console, only shows me the last element ("Guillermo Barcia").

There I leave the Person class

class Persona : IComparable<Persona>  
{
     #region Atributos
     private static string dni;
     private static string nombre;
     #endregion
     #region Propiedades
     public string Dni { get => dni; set => dni = value; }
     public string Nombre { get => nombre; set => nombre = value; }
     #endregion
     #region Constructores
     public Persona(string dn, string nom)
     {
          dni = dn;
          nombre = nom;
     }
     public Persona() { }
     #endregion
     #region CompareTo
     public int CompareTo(Persona other)
     {
           throw new NotImplementedException();
     }
     #endregion
     #region ToString
     public string ToString()
     {
           return "Nombre: " + nombre + "\n" +
                  "DNI: " + dni;
     }
     #endregion
}
    
asked by Jesus Romero 27.11.2018 в 10:13
source

1 answer

4

The problem that you have is a bit complicated to see for someone new to the programming.

The point is that you have marked your private variables dni and nombre as static . This means that in all instances of Persona , these variables are the same, so when assigning names in the constructor of the class, you are modifying these private variables in all previous instances.

Simply delete the static modifier and it should work correctly.

P.D.

I think you have created the toString method (with minuscule the first) to print the data. Actually, it is more correct to overwrite the default method ToString . For this, the definition must be public override string ToString() . override indicates that you overwrite the method.

    
answered by 27.11.2018 / 10:45
source