C# Overriding ToString Method


Microsoft has an article on overriding the ToString() method in the web page called Formatting Types in .NET.

Default

using System;
public class Automobile
{
   // No implementation. All members are inherited from Object.
}
public class Example
{
   public static void Main()
   {
      Automobile firstAuto = new Automobile();
      Console.WriteLine(firstAuto);
   }
}
// The example displays the following output:
//       Automobile

This type of behaviour may not be what you need.

Overriding

Below is an example of overriding the ToString() method. You use the override keyword in C#.

using System;

public class Temperature
{
   private decimal temp;
   public Temperature(decimal temperature)
   {
      this.temp = temperature;   
   }
   public override string ToString()
   {
      return this.temp.ToString("N1") + "°C";
   }
}
public class Example
{
   public static void Main()
   {
      Temperature currentTemperature = new Temperature(23.6m);
      Console.WriteLine("The current temperature is " +
                        currentTemperature.ToString());
   }
}
// The example displays the following output:
//       The current temperature is 23.6°C.