Override ToString to do the custom formatting in CSharp

Description

The following code shows how to override ToString to do the custom formatting.

Example


using System;/* www. ja v  a2 s.  com*/

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 code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor