Override ToString() method in C#

Any Object that derives from System.Object implements a method ToString() which upon calling, return the fully qualified
name of the class.

We can override the ToString() method to return more meaningful Results

For ex:

Let’s have a console application with a class called Customer, defined like:

class Customer
{
        public Customer(string firstName, string lastName, string address, string phone)
       {
                FirstName = firstName;
                LastName = lastName;
                Address = address;
                Phone = phone;
       }
 
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Address { get; set; }
      public string Phone { get; set; }
 
}

Now in the main(), call constructor of the class Customer:

Customer customer = new Customer("Monte", "Carlo", "Street No 122, LA", "000-111222333");
 
 
If we call ToString() on customer, it will return the class name (Customer)
 
Console.WriteLine(customer.ToString());
 
Output:
Customer
 
Now, Override ToString() for Customer class like:
 
public override string ToString()
{
return String.Format("Customer Details: \nFirst Name - {0} \nLast Name - {1} \nAddress - {2} \nPhone - {3}", FirstName, LastName, Address, Phone);
}
 
 
Calling ToString() on Customer object will now return more meaningful result as:
 
Console.WriteLine(customer.ToString());

output:

Customer Details: First Name – Monte Last Name – Carlo Address – Street No 122, LA

Phone – 000-111222333

150 150 Burnignorance | Where Minds Meet And Sparks Fly!