
The ToString Method and Format Strings
Relying on the default ToString method or overriding ToString is appropriate when an object has a single string representation. However, the value of an object often has multiple representations. For example, a temperature can be expressed in degrees Fahrenheit, degrees Celsius, or degrees Kelvin. Similarly, the integer value 10 can be represented as 10, 10.0, 1.0e01, or $10.00.
To enable a single value to have multiple string representations, the .NET Framework for Silverlight uses format strings. A format string is a string that contains one or more predefined format specifiers, which are single characters or groups of characters that define how the ToString method should format its output. The format string is then passed as a parameter to the object's ToString method and determines how the string representation of that object's value should appear.
All numeric types, enumeration values, and the DateTime type support a predefined set of format specifiers. However, support for format strings is not limited to the .NET Framework's primitive data types. You can also use format strings to define multiple string representations of your application-defined data types.
Standard Format Strings
A standard format string includes a single format specifier that defines the string representation of an object. In some cases, the correspondence between a standard format string and an object’s string representation is direct. This is true of the standard format strings supported by enumeration members. Using a standard format string is also the most common method for implementing application-defined format strings.
Format strings for enumeration types and for most application-defined types directly control the string representation of a value. The format strings passed to an enumeration value’s ToString method determine whether the value is displayed using its string name (the "G" and "F" format specifiers), its underlying integral value (the "D" format specifier), or its hexadecimal value (the "X" format specifier). The following example illustrates the use of standard format strings to format a DayOfWeek value.
Module Example
Public Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
Dim thisDay As DayOfWeek = DayOfWeek.Monday
Dim formatStrings() As String = {"G", "F", "D", "X"}
For Each formatString As String In formatStrings
outputBlock.Text += thisDay.ToString(formatString) + vbCrLf
Next
End Sub
End Module
' The example displays the following output:
' Monday
' Monday
' 1
' 00000001
using System;
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
DayOfWeek thisDay = DayOfWeek.Monday;
string[] formatStrings = {"G", "F", "D", "X"};
foreach (string formatString in formatStrings)
outputBlock.Text += thisDay.ToString(formatString) + "\n";
}
}
// The example displays the following output:
// Monday
// Monday
// 1
// 00000001
For date and time values and all numeric values, a standard format string is in some cases an alias for a set of property values. For example, the "C" format specifier formats a number as a currency value. When you call the ToString method with the "C" format specifier as the only parameter, the following property values from the current culture’s NumberFormatInfo object are used to define the string representation of the numeric value:
The CurrencySymbol property, which returns a string that contains the current culture’s currency symbol.
The CurrencyNegativePattern or CurrencyPositivePattern property, which returns integers that determine the following:
The placement of the currency symbol.
Whether negative values are indicated by a leading negative sign, a trailing negative sign, or parentheses.
Whether a space appears between the numeric value and the currency symbol.
The CurrencyDecimalDigits property, which defines the set of decimal digits.
The CurrencyDecimalSeparator property, which defines the decimal separator symbol.
The CurrencyGroupSeparator property, which defines the group separator symbol.
The CurrencyGroupSizes property, which defines the number of digits in each group to the left of the decimal.
Other standard format strings for numeric values or date and time values are aliases for custom format strings stored by a property. For example, calling the ToString method of a date and time value with the "D" format specifier displays the date and time by using the custom format string stored in the current culture’s DateTimeFormatInfo..::.LongDatePattern property. The following example illustrates the relationship between the custom format string and the string representation of a date.
Imports System.Globalization
Module Example
Public Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
Dim date1 As Date = #6/30/2009#
outputBlock.Text += String.Format("'{0}' format string: {1}", _
CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern, _
date1.ToString("D")) + vbCrLf
End Sub
End Module
' The example displays the following output when run on a system whose
' current culture is en-US:
' 'dddd, MMMM dd, yyyy' format string: Tuesday, June 30, 2009
using System;
using System.Globalization;
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
DateTime date1 = new DateTime(2009, 6, 30);
outputBlock.Text += String.Format("'{0}' format string: {1}\n",
CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern,
date1.ToString("D"));
}
}
// The example displays the following output when run on a system whose
// current culture is en-US:
// 'dddd, MMMM dd, yyyy' format string: Tuesday, June 30, 2009
For information about standard numeric formatting strings, see Standard Numeric Format Strings. For information about standard date and time format strings, see Standard Date and Time Format Strings.
You can also use standard format strings to define the string representation of an application-defined object that is produced by the object’s ToString method. For example, a Temperature class can internally store the temperature in degrees Celsius and use format specifiers to represent the value of the Temperature object in degrees Celsius, degrees Fahrenheit, and degrees Kelvin. The following example provides an illustration.
Public Class Temperature
Private m_Temp As Decimal
Public Sub New(temperature As Decimal)
Me.m_Temp = temperature
End Sub
Public ReadOnly Property Celsius() As Decimal
Get
Return Me.m_Temp
End Get
End Property
Public ReadOnly Property Kelvin() As Decimal
Get
Return Me.m_Temp + 273.15d
End Get
End Property
Public ReadOnly Property Fahrenheit() As Decimal
Get
Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2)
End Get
End Property
Public Overrides Function ToString() As String
Return Me.ToString("C")
End Function
Public Overloads Function ToString(format As String) As String
' Handle null or empty string.
If Not String.IsNullOrEmpty(format) Then format = format.Trim()
If String.IsNullOrEmpty(format.Trim()) Then format = "C"
' Convert temperature to Fahrenheit and return string.
Select Case format.ToUpper()
Case "F"
Return Me.Fahrenheit.ToString("N2") & " °F"
' Convert temperature to Kelvin and return string.
Case "K"
Return Me.Kelvin.ToString("N2") & " °K"
' Return temperature in Celsius.
Case "C"
Return Me.Celsius.ToString("N2") & " °C"
Case Else
Throw New FormatException(String.Format("The '{0}' format string is not supported.", format))
End Select
End Function
End Class
Public Module Example
Public Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
Dim temp1 As New Temperature(0d)
outputBlock.Text += temp1.ToString() + vbCrLf
outputBlock.Text += temp1.ToString("C") + vbCrLf
outputBlock.Text += temp1.ToString("F") + vbCrLf
outputBlock.Text += temp1.ToString("K") + vbCrLf
Dim temp2 As New Temperature(-40d)
outputBlock.Text += temp2.ToString() + vbCrLf
outputBlock.Text += temp2.ToString("C") + vbCrLf
outputBlock.Text += temp2.ToString("F") + vbCrLf
outputBlock.Text += temp2.ToString("K") + vbCrLf
Dim temp3 As New Temperature(16d)
outputBlock.Text += temp3.ToString() + vbCrLf
outputBlock.Text += temp3.ToString("C") + vbCrLf
outputBlock.Text += temp3.ToString("F") + vbCrLf
outputBlock.Text += temp3.ToString("K") + vbCrLf
outputBlock.Text += String.Format("The temperature is now {0:F}.", temp3) + vbCrLf
End Sub
End Module
' The example displays the following output:
' 0.00 °C
' 0.00 °C
' 32.00 °F
' 273.15 °K
' -40.00 °C
' -40.00 °C
' -40.00 °F
' 233.15 °K
' 16.00 °C
' 16.00 °C
' 60.80 °F
' 289.15 °K
' The temperature is now 16.00 °C.
public class Temperature
{
private decimal m_Temp;
public Temperature(decimal temperature) {
this.m_Temp = temperature;
}
public decimal Celsius {
get { return this.m_Temp; }
}
public decimal Kelvin {
get { return this.m_Temp + 273.15m; }
}
public decimal Fahrenheit {
get { return Math.Round((decimal)this.m_Temp * 9 / 5 + 32, 2); }
}
public override string ToString()
{
return this.ToString("C");
}
public string ToString(string format)
{
// Handle null or empty string.
if (! String.IsNullOrEmpty(format))
format = format.Trim();
if (String.IsNullOrEmpty(format))
format = "C";
switch (format.ToUpper())
{
// Convert temperature to Fahrenheit and return string.
case "F":
return this.Fahrenheit.ToString("N2") + " °F";
// Convert temperature to Kelvin and return string.
case "K":
return this.Kelvin.ToString("N2") + " °K";
// Return temperature in Celsius.
case "C":
return this.Celsius.ToString("N2") + " °C";
default:
throw new FormatException(String.Format("The '{0}' format string is not supported.", format));
}
}
}
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
Temperature temp1 = new Temperature(0m);
outputBlock.Text += temp1.ToString() + "\n";
outputBlock.Text += temp1.ToString("C") + "\n";
outputBlock.Text += temp1.ToString("F") + "\n";
outputBlock.Text += temp1.ToString("K") + "\n";
Temperature temp2 = new Temperature(-40m);
outputBlock.Text += temp2.ToString() + "\n";
outputBlock.Text += temp2.ToString("C") + "\n";
outputBlock.Text += temp2.ToString("F") + "\n";
outputBlock.Text += temp2.ToString("K") + "\n";
Temperature temp3 = new Temperature(16m);
outputBlock.Text += temp3.ToString() + "\n";
outputBlock.Text += temp3.ToString("C") + "\n";
outputBlock.Text += temp3.ToString("F") + "\n";
outputBlock.Text += temp3.ToString("K") + "\n";
outputBlock.Text += String.Format("The temperature is now {0:F}.\n", temp3);
}
}
// The example displays the following output:
// 0.00 °C
// 0.00 °C
// 32.00 °F
// 273.15 °K
// -40.00 °C
// -40.00 °C
// -40.00 °F
// 233.15 °K
// 16.00 °C
// 16.00 °C
// 60.80 °F
// 289.15 °K
// The temperature is now 16.00 °C.
Custom Format Strings
In addition to the standard format strings, the .NET Framework defines custom format specifiers for both numeric values and date and time values. A custom format string consists of one or more custom format specifiers that define the string representation of a value. For example, the custom date and time format string "yyyy/mm/dd hh:mm:ss.ffff t zzz" converts a date to its string representation in the form 2008/11/15 07:45:00.0000 P -08:00 for the en-US culture. Similarly, the custom format string "0000" converts the integer value 12 to "0012".
Many standard format strings are aliases for custom format strings that are defined by properties of the DateTimeFormatInfo or NumberFormatInfo objects. Custom format strings also offer considerable flexibility in providing application-defined formatting for numeric or date and time values.
For a complete list of custom format strings, see Custom Date and Time Format Strings and Custom Numeric Format Strings.