How to return the name of an instance of a class?

2

In order not to have to manually write the data after an update on the objects, I decided to create a method of type static to be accessed by passing the object as a parameter.

    public static void Relatorio(Trem trem)
    { 

        Console.WriteLine($"{trem} - PESO ATUAL:       {trem.getPesoVagao()}");
        Console.WriteLine($"{trem} - PESO SUPORTADO:   {trem.getCargaMAX()}");
        Console.WriteLine($"{trem} - CARGA DISPONÍVEL: {trem.CargaRestante()}");

        Console.WriteLine();
        Console.WriteLine();
    }

ThiswouldpreventmefromwritingthereportinMain()wheneverImadeachangetotheobject,butthereturnednamethatshouldbe"T2" is returning as SobrecargaDeMetodos.Trem .

I call the method as follows passing the object to be parsed as parameter. The part of showing the result works perfectly, but the name does not.

Trem.Relatorio(T2);
    
asked by anonymous 30.09.2018 / 20:22

2 answers

-2

Another option is to add a Nome property to your Trem class. This way all trains would have a Nome

public class Trem{
    public string Nome{get; set;}
    //...
}

And every time you create a train, you assign a name. var t = new Trem(){Nome = "t2"}; . And your report would use its property:

Console.WriteLine($"{trem.Nome} - PESO ATUAL:       {trem.getPesoVagao()}");
//...
    
05.10.2018 / 17:38
6

This is a wrong concept. First there is no instance name, variable name exists. It may be that in this case a name is equal to the name of the variable, but it can not always represent any name in a variable name. But there is also an error in understanding what a variable is. Variables are local and do not go from one context to another, so what you want does not make sense, in fact what is printing is not what you are imagining. The solution to this is very simple:

public static void Relatorio(Trem trem, string nome) {
    WriteLine($"{nome} - PESO ATUAL:       {trem.getPesoVagao()}");

There he calls:

Trem.Relatorio(T2, "T2");

If you think you can change this name (which seems strange to me, but I will not discuss other possible errors in this design), you can even use:

Trem.Relatorio(T2, nameof(T2));

This just ensures that if the variable name is changed it will give a compile error in the string , so it forces you to change the name there too.

Maybe you have other bugs concepts in it.

    
30.09.2018 / 20:50