How to override the ToString() method : ToString « Class « C# / CSharp Tutorial






using System;

public class Employee
{
  public string firstName;
  public string lastName;

  public Employee(string firstName, string lastName)
  {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public override string ToString()
  {
    return firstName + " " + lastName;
  }
}

class MainClass
{
  public static void Main()
  {
    Employee myEmployee = new Employee("A", "M");
    Employee myOtherEmployee = new Employee("B", "N");

    Console.WriteLine("myEmployee.ToString() = " + myEmployee.ToString());
    Console.WriteLine("myOtherEmployee.ToString() = " + myOtherEmployee.ToString());
  }
}
myEmployee.ToString() = A M
myOtherEmployee.ToString() = B N








7.48.ToString
7.48.1.How to override the ToString() method
7.48.2.mark override when overriding ToString
7.48.3.Demonstrate ToString()
7.48.4.override ToString
7.48.5.Format value in ToString method
7.48.6.override ToString method twices