0

I'm a beginner of C#, I have this class:

public Dipendente(String Id, String Nome, String Cognome, Contratto TipoContratto, DateTime Data_assunzione, double Stipendio, Dipendente Tutor)
{
    this.Id = Id;
    this.Nome = Nome;
    this.Cognome = Cognome;
    this.TipoContratto = TipoContratto;
    this.DataAssunzione = Data_assunzione;
    this.StipendioMensile = Stipendio;
    this.Tutor = Tutor;
}

public static Dipendente GetDipendenteFromPersona(Persona persona, Contratto contratto, DateTime data_assunzione, double stipendio, Dipendente tutor)
{
    Dipendente result = null;
    result = new Dipendente(persona.Id, persona.Nome, persona.Cognome, contratto, data_assunzione, stipendio, tutor);
    return result;
}

In the main I have a list of objects like this:

Dipendente dip1 = Dipendente.GetDipendenteFromPersona(p1, lstContratti[1], new DateTime(2000, 10, 10), 1000, null);
List<Dipendente> lstDipendenti = new List<Dipendente> {dip1, dip2, dip3, dip4, dip5, dip6, dip7, dip8};

I need to print each item in the list with his property, which is the best way to do that?

I've tried with this but obviously didn't get property values:

foreach (Dipendente dip in lstDipendenti)
{
    System.Diagnostics.Debug.WriteLine(dip);
}
marko
  • 487
  • 1
  • 6
  • 15

1 Answers1

2

First, let each class (Dipendente) instance speak for itself, .ToString() is the very place for this:

Returns a string that represents the current object.

...It converts an object to its string representation so that it is suitable for display...

 public class Dipendente 
 {
     ...

     public override string ToString() 
     {  
         // Put here all the fields / properties you mant to see in the desired format
         // Here we have "Id = 123; Nome = John; Cognome = Smith" format
         return string.Join("; ",
           $"Id = {Id}",
           $"Nome = {Nome}", 
           $"Cognome = {Cognome}"  
         );
     }
 }

then you can put

 foreach (Dipendente dip in lstDipendenti)
 {
     // Or even System.Diagnostics.Debug.WriteLine(dip);
     System.Diagnostics.Debug.WriteLine(dip.ToString());
 }
Community
  • 1
  • 1
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215