Valerie Meunier

Valerie Meunier

  • 958
  • 693
  • 72.1k

overriding ToString() method

Jul 13 2021 1:42 PM

Hi

I wonder whether there are advantages of overriding ToString() method. If yes, which ones?. 

This code produces 3 times the same output, so why overriding the ToString() method?

Thanks

using System;
class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee() { Name = "Luke", Age= 40 };
        Console.WriteLine(emp.ToString());
        Console.WriteLine(emp.Name + " " + emp.Age);
        emp.MyMethod();
    }
}

public class Employee
{
    public string Name;
    public int Age;

    public override string ToString()
    {
        return Name + " " + Age;
    }

    public void MyMethod()
    {
        Console.WriteLine(Name + " " + Age);
    }


Answers (3)