Override ToString to do the custom formatting : IFormattable « Data Types « C# / C Sharp






Override ToString to do the custom formatting

  

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(3.6m);
      Console.WriteLine("The current temperature is {0}.", currentTemperature);
   }
}

//The current temperature is 3.6C.

   
    
  








Related examples in the same category

1.IFormattable Interface formats the value of an object into a string
2.Format a DateTime with CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern