IFormattable Interface
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
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
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



