Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
System Namespace
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
IFormattable Interface

Updated: November 2007

Provides functionality to format the value of an object into a string representation.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Visual Basic (Declaration)
<ComVisibleAttribute(True)> _
Public Interface IFormattable
Visual Basic (Usage)
Dim instance As IFormattable
C#
[ComVisibleAttribute(true)]
public interface IFormattable
Visual C++
[ComVisibleAttribute(true)]
public interface class IFormattable
J#
/** @attribute ComVisibleAttribute(true) */
public interface IFormattable
JScript
public interface IFormattable

IFormattable is implemented by the base data types.

A format describes the appearance of an object when it is converted to a string. A format can be either standard or custom. A standard format takes the form Axx, where A is an alphabetic character called the format specifier, and xx is a nonnegative integer called the precision specifier. The format specifier controls the type of formatting applied to the value being represented as a string. The precision specifier controls the number of significant digits or decimal places in the string, if applicable. A custom format consists of one or more alphabetic characters that together define a single format string.

When a format includes symbols that vary by culture, such as the currency symbol represented by the "C" and "c" standard numeric format specifiers, a formatting object (in the case of the "C" and "c" specifiers, a NumberFormatInfo object) supplies the actual characters used in the string representation. A method might include a parameter to pass an IFormatProvider object that supplies a formatting object, or the method might use the default formatting object, which contains the symbol definitions for the current thread. The current thread typically uses the same set of symbols used system-wide by default.

For details on standard and custom format strings for the numeric types, see Numeric Format Strings. For details on standard and custom format strings for the DateTime structure, see Date and Time Format Strings.

Notes to Implementers:

Classes that require more control over the formatting of strings than Object..::.ToString provides should implement IFormattable, whose ToString method uses the current thread's CurrentCulture property.

A class that implements IFormattable must support the "G" (general) formatting code. Besides the "G" code, the class can define the list of formatting codes that it supports.

For more information on formatting and formatting codes, see Formatting Overview.

The following example demonstrates how to define a type that implements the IFormattable interface. The example also shows how to call the ToString method of the IFormattable interface.

Visual Basic
Public Class Point : Implements IFormattable
    Dim x, y As Integer 

    Public Sub New(x As Integer, y As Integer)
        Me.x = x
        Me.y = y
    End Sub

    Public Overrides Function ToString() As String
        Return ToString(Nothing, Nothing)
    End Function

    Public Overloads Function ToString(format As String) As String
       Return ToString(format, Nothing)
    End Function

    Public Overloads Function ToString(format As String, _
                                       fp As IFormatProvider) As String _
            Implements IFormattable.ToString
        ' If no format specifier is passed, display like this: (x, y).
        If String.IsNullOrEmpty(format) Then _
            Return String.Format("({0}, {1})", x, y)

        ' For "x" formatting, return just the x value as a string
        If format.ToLower = "x" Then _
            Return x.ToString()

        ' For "y" formatting, return just the y value as a string
        If format.ToLower = "y" Then _
            Return y.ToString()

        ' For any unrecognized format, throw an exception.
        Throw New FormatException(String.Format("Invalid format string: '{0}'.", format))
    End Function
End Class

Public Module App
    Public Sub Main()
        ' Create the object.
        Dim p As New Point(5, 98)

        ' Test ToString with no formatting.
        Console.WriteLine("This is my point: " + p.ToString())

        ' Use custom formatting style "x"
        Console.WriteLine("The point's x value is {0:x}", p)

        ' Use custom formatting style "y"
        Console.WriteLine("The point's y value is {0:y}", p)

        Try 
            ' Use an invalid format; FormatException should be thrown here.
            Console.WriteLine("Invalid way to format a point: {0:XYZ}", p)
        Catch e As FormatException
            Console.WriteLine("The last line could not be displayed: {0}", e.Message)
        End Try
    End Sub
End Module

' This code produces the following output.
' 
'  This is my point: (5, 98)
'  The point's x value is 5
'  The point's y value is 98
'  The last line could not be displayed: Invalid format string: 'XYZ'.

C#
using System;

class Point : IFormattable
{
    public int x, y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override String ToString() { return ToString(null, null); }

    public String ToString(String format, IFormatProvider fp)
    {
        // If no format is passed, display like this: (x, y).
        if (format == null) return String.Format("({0}, {1})", x, y);

        // For "x" formatting, return just the x value as a string
        if (format == "x") return x.ToString();

        // For "y" formatting, return just the y value as a string
        if (format == "y") return y.ToString();

        // For any unrecognized format, throw an exception.
        throw new FormatException(String.Format("Invalid format string: '{0}'.", format));
    }
}


public sealed class App
{
    static void Main()
    {
        // Create the object.
        Point p = new Point(5, 98);

        // Test ToString with no formatting.
        Console.WriteLine("This is my point: " + p.ToString());

        // Use custom formatting style "x"
        Console.WriteLine("The point's x value is {0:x}", p);

        // Use custom formatting style "y"
        Console.WriteLine("The point's y value is {0:y}", p);

        try 
        {
            // Use an invalid format; FormatException should be thrown here.
            Console.WriteLine("Invalid way to format a point: {0:XYZ}", p);
        }
        catch (FormatException e)
        {
            Console.WriteLine("The last line could not be displayed: {0}", e.Message);
        }
    }
}

// This code produces the following output.
// 
//  This is my point: (5, 98)
//  The point's x value is 5
//  The point's y value is 98
//  The last line could not be displayed: Invalid format string: 'XYZ'.

Visual C++
using namespace System;

public value struct Point : IFormattable
{
private:
    int x;

private:
    int y;

public:
    property int X
    {
        int get()
        {
            return x;
        }
        void set(int value)
        {
            x = value;
        }
    }

public:
    property int Y
    {
        int get()
        {
            return y;
        }
        void set(int value)
        {
            y = value;
        }
    }

public:
    Point(int x, int y)
    {
        this->x = x;
        this->y = y;
    }

public:
    virtual String^ ToString() override
    {
        return ToString(nullptr, nullptr);
    }

public:
    virtual String^ ToString(String^ format, IFormatProvider^ formatProvider)
    {
        // If no format is passed, display like this: (x, y).
        if (format == nullptr)
        {
            return String::Format("({0}, {1})", x, y);
        }

        // For "x" formatting, return just the x value as a string
        if (format == "x")
        {
            return x.ToString();
        }

        // For "y" formatting, return just the y value as a string
        if (format == "y")
        {
            return y.ToString();
        }

        // For any unrecognized format, throw an exception.
        throw gcnew FormatException(String::Format(
            "Invalid format string: '{0}'.", format));
    }
};

int main()
{
    // Create the object.
    Point p = Point(5, 98);

    // Test ToString with no formatting.
    Console::WriteLine("This is my point: " + p.ToString());

    // Use custom formatting style "x"
    Console::WriteLine("The point's x value is {0:x}", p);

    // Use custom formatting style "y"
    Console::WriteLine("The point's y value is {0:y}", p);

    try
    {
        // Use an invalid format;
        // FormatException should be thrown here.
        Console::WriteLine(
            "Invalid way to format a point: {0:XYZ}", p);
    }
    catch (FormatException^ e)
    {
        Console::WriteLine(
            "The last line could not be displayed: {0}",
            e->Message);
    }
}

// This code produces the following output.
//
//  This is my point: (5, 98)
//  The point's x value is 5
//  The point's y value is 98
//  The last line could not be displayed: Invalid format string: 'XYZ'.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Example improvement      fernandonajera   |   Edit   |  
I think the example can be improved. After all, the ToString() method should use the given FormatProvider information for its rendering. So, everytime it calls to x.ToString(), y.ToString() or String.Format, all the items should be formatted using the argument fp. I think the following example is better (I have used double values so you can see the differences):

    class Point : IFormattable
{
public double x, y;

public Point (double x, double y)
{
this.x = x;
this.y = y;
}

public override String ToString () { return ToString (null, null); }

public String ToString (String format, IFormatProvider fp)
{
// If no format is passed, display like this: (x, y).
if (format == null)
return String.Format ("({0}, {1})", x.ToString (fp), y.ToString (fp));

// For "x" formatting, return just the x value as a string
if (format == "x")
return x.ToString (fp);

// For "y" formatting, return just the y value as a string
if (format == "y")
return y.ToString (fp);

// For any unrecognized format, throw an exception.
throw new FormatException (String.Format ("Invalid format string: '{0}'.", format));
}

}

If you call it like this:

Point x = new Point (3.3, 5);
Debug.WriteLine (x.ToString (null, CultureInfo.InvariantCulture));
Debug.WriteLine (x.ToString (null, CultureInfo.GetCultureInfo ("es-ES")));

then you will see the difference:

(3.3, 5)
(3,3, 5)

By the way, I am still not happy, as we are hardcoding the comma as list separator; that separator is also culture-dependent, and theoretically it could be retrieved. However I don't know how to get that value from the IFormatProvider object...

In any case, for integer values it does not matter if the IFormatProvided argument is used or not - so the given example is indeed right for integers. But I think it is worth to notice this point.
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker