Overview
- Enables 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

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




