Sunday, October 21, 2007

The IFormattable interface

Implementing the IFormattable interface let's you do much more with the ToString() method if you're developing text-based applications or are trying to create strings out of object fields.

To implement the IFormattable interface, you have to create a ToString method that accepts a format string and an IFormatProvider object. The IFormatProvider object isn't relevant but the format string can be used, such as to return only one field of an object. Here's a sample implementation:

class TimeInterval : IFormattable {

...

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

public string ToString (string format, IFormatProvider formatProvider) {

if (format == null) {
return this.Hour.ToString() + ":" + this.Minute.ToString();
} else if (format == "h") {
return this.Hour.ToString();
} else if (format == "m") {
return this.Minute.ToString();
} else throw new Exception("Invalid format specified");
}
}

To use the new method, you could provide a format string to either string.Format or Console.WriteLine. Example:
TimeInterval timeInterval = new TimeInterval();
Console.WriteLine("{0:h} hours and {0:m} minutes", timeInterval);
Console.WriteLine("{0,2:h}:{0,2:m}", timeInterval); //the ",2" specifies the minimum number of characters in the resulting string - if positive, the output is left-padded, otherwise it is right-padded

No comments: