IFormattable Interface

Overview

  • Enable classes to display themselves with greater control than ToString.

Examples

Custom Formats

struct MyPoint: IFormattable
{
    private int _x;
    private int _y;
 
    public int X
    {
        get { return this._x; }
    }
 
    public int Y
    {
        get { return this._y; }
    }
 
    public MyPoint(int x, int y)
    {
        this._x = x;
        this._y = y;
    }
 
    #region IFormattable Members
    public string ToString(string format, IFormatProvider formatProvider)
    {
        string formattedString;
        if (format != null) { format = format.ToLower(); }
 
        switch (format)
        {
            case null: 
                formattedString = String.Format("({0}, {1})", this.X, this.Y);
                break;
            case "x":
                formattedString = this.X.ToString();
                break;
            case "y":
                formattedString = this.Y.ToString();
                break;
            default: 
                throw new FormatException(String.Format("Invalid format string: '{0}'.", format));
        }
 
        return formattedString;
    }
    #endregion
}
MyPoint a = new MyPoint(5, 15);
Console.WriteLine("The point's value is {0}", a);
Console.WriteLine("The point's x value is {0:x}", a);
Console.WriteLine("The point's y value is {0:y}", a);
 
// Prints:
// The point's value is (5, 15)
// The point's x value is 5
// The point's y value is 15