Is it possible to do several toString () of the same class in c #?

3

I have a defined class which I want to take two methods toString (), especially for the aesthetics of the program, I want in one case to display several variables (for a listbox) and for another only one variable (for a combobox) , in the following way.

Or in what way would be better, especially because I add the object as such to the components (listbox and combobox).

public class ZonaSistema
{

//Declaración de atributos
private int idZona;
private int numeroZona;
private string descripcionZona;
private int particionZona; 

    //Sobrecarga al método toString
    public override string ToString()
    {
        return "Zona: " + this.numeroZona + "\tDescripción: " + this.descripcionZona + "\tPartición: " + this.particionZona;
    }

    public override string ToString()
    {
        return "Zona: " + this.numeroZona;
    }
}
    
asked by Daniel Cadena 03.10.2018 в 06:57
source

1 answer

6

You can only override the ToString() method, but you can do the overloads that you require, for example:

public class Impuesto
{
    public int Valor { get; set; }
    public int Year { get; set; }
    public override string ToString()
    {
        return Valor.ToString();
    }
    public string ToString(string format)
    {
        return Valor.ToString(format);
    }
    ///puedes seguir sobre cargando el metodo ToString según requieras
}

For your case I would recommend that you define a property that returns the full name and that property shows it in your listbox. Your Class could look like this:

public class ZonaSistema
{
    private int IdZona { get; set; }
    private int NumeroZona { get; set; }
    private string DescripcionZona { get; set; }
    private int ParticionZona { get; set; }

    public string NombreCompleto
    {
        get
        {
            return $"Zona: {NumeroZona}\tDescripción: {DescripcionZona }\tPartición: {ParticionZona}";
        }
    }

    public override string ToString()
    {
        return "Zona: " + NumeroZona;
    }
}
    
answered by 03.10.2018 в 07:10