Show object value instead of class name

Asked

Viewed 35 times

2

I’m doing a simple application registration in array, but when run appears the following result in the console instead of the information I passed in the parameter.

aparece o nome da classe

Follows the code:

static void Main(string[] args)
    {
        Veiculo[] veiculosArray = new Veiculo[10];

        veiculosArray[0] = new Veiculo("BMW", "DSR6646");

        Console.WriteLine(veiculosArray[0]);
        Console.ReadKey();
        Console.ReadKey();

    }

Vehicle Class:

class Veiculo
{
    public string Modelo { get; set; } = string.Empty;
    public string Placa { get; set; } = string.Empty;

    public Veiculo(string modelo, string placa)
    {
        Modelo = modelo;
        Placa = placa;
    }

}
  • Now you can vote on everything on the site, take a look at [tour] how it works. You can vote here too, the vote is different from the acceptance.

1 answer

1


The specific reason for this error is that you have not created a method ToString() for its class, then the compiler uses a pattern that returns the class name. Overwriting this method solves this problem, still has several other conceptual in the class and all use, even if it is an exercise.

using static System.Console;

public class Program {
    public static void Main() {
        var veiculosArray = new Veiculo[10] ;
        veiculosArray[0] = new Veiculo("BMW", "DSR6646");
        WriteLine(veiculosArray[0]);
    }
}
class Veiculo {
    public string Modelo { get; set; } = "";
    public string Placa { get; set; } = "";
    public Veiculo(string modelo, string placa) {
        Modelo = modelo;
        Placa = placa;
    }
    public override string ToString() => Placa;
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.