Mono Class Library: System.IFormattable Overview | Members

System.IFormattable.ToString Method

Returns a string representation of the value of the current instance. [Edit]

public string ToString (string format, IFormatProvider formatProvider)

Parameters

format
A string that specifies the format of the returned string. If format is a null reference or the empty string, the default format defined for the type of the current instance is used. [Edit]
formatProvider
Documentation for this section has not yet been entered. [Edit]

Returns

A string containing the value of the current instance formatted in accordance with format and formatProvider . [Edit]

Exceptions

TypeReason
FormatExceptionThe specified format is invalid or cannot be used with the type of the current instance. [Edit]

Remarks

Operation

Conforming implementations do not throw an exception when format and/or formatProvider are null references. If formatProvider is a null reference, the string is constructed using a system-supplied formatting object containing information for the current system culture. If format is null, the string is constructed using a system-supplied default format appropriate for the type of the current instance.

If the object returned by formatProvider supplies a culture-specific representation of symbols or patterns included in format, the returned string is required to use the information supplied by formatProvider .

Note to Inheritors
Implement to allow consumers of a class to use format strings and formatting objects to control the way in which the class is represented as a string.

[Edit]

Example

The following example demonstrates using the IFormattable.ToString(string, IFormatProvider) method to display values in a variety of formats. The current system culture is U.S. English, which provides the default values for the formatProvider parameter of IFormattable.ToString(string, IFormatProvider).

C# Example
using System;
class FormattableExample {
    public static void Main() {
    double d = 123.12345678901234;
    string[] formats = {"C","E","e","F","G","N","P","R"};
    for (int i = 0; i< formats.Length;i++) 
        Console.WriteLine("{0:R} as {1}:  {2}",d,formats[i],d.ToString(formats[i],null));

    string[]intFormats = {"D","x","X"};
    int val = 255;
    for (int i = 0; i< intFormats.Length;i++) 
        Console.WriteLine("{0} as {1}:  {2}",val,intFormats[i],val.ToString(intFormats[i],null));

    }
}

The output is

123.12345678901234 as C: $123.12
123.12345678901234 as E: 1.231235E+002
123.12345678901234 as e: 1.231235e+002
123.12345678901234 as F: 123.12
123.12345678901234 as G: 123.123456789012
123.12345678901234 as N: 123.12
123.12345678901234 as P: 12,312.35 %
123.12345678901234 as R: 123.12345678901234
255 as D: 255
255 as x: ff
255 as X: FF

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0