IFormattable.ToString Method
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Formats the value of the current instance using the specified format.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- format
- Type: System.String
The String specifying the format to use.
-or-
null to use the default format defined for the type of the IFormattable implementation.
- formatProvider
- Type: System.IFormatProvider
The IFormatProvider to use to format the value.
-or-
null to obtain the numeric format information from the current locale setting of the operating system.
Return Value
Type: System.StringA String containing the value of the current instance in the specified format.
NumberFormatInfo, DateTimeFormatInfo and CultureInfo implement the IFormatProvider interface.
NumberFormatInfo supplies numeric formatting information, such as the characters to use for decimal and thousand separators and the spelling and placement of currency symbols in monetary values.
DateTimeFormatInfo supplies date- and time-related formatting information, such as the position of the month, the day and the year in a date pattern.
CultureInfo contains the default formatting information in a specific culture, including the numeric format information and date- and time-related formatting information.
The following code example demonstrates implementing the ToString method. This code example is part of a larger example provided for the IFormattable class.
public override String ToString() { return ToString(null, null); } public String ToString(String format, IFormatProvider fp) { if (String.IsNullOrEmpty(format)) format = "G"; // If G format specifier is passed, display like this: (x, y). if (format.ToLower() == "g") return String.Format("({0}, {1})", x, y); // For "x" format specifier, return just the x value as a string if (format.ToLower() == "x") return x.ToString(); // For "y" format specifier, return just the y value as a string if (format.ToLower() == "y") return y.ToString(); // For any unrecognized format specifier, throw an exception. throw new FormatException(String.Format("Invalid format string: '{0}'.", format)); }