Information Technology Reference
In-Depth Information
case "n" :
case "G" :
default :
return Name;
}
}
Adding this function gives your clients the capability to specify the pres-
entation of their customer data:
IFormattable c1 = new Customer ();
Console .WriteLine( "Customer record: {0}" ,
c1.ToString( "nrp" , null ));
Any implementation of IFormattable.ToString() is specific to the type, but
you must handle certain cases whenever you implement the IFormattable
interface. First, you must support the general format, "G". Second, you
must support the empty format in both variations: "" and null. All three
format specifiers must return the same string as your override of the
Object.ToString() method. The .NET Base Class Library (BCL) calls
IFormattable.ToString() instead of Object.ToString() for every type that
implements IFormattable. The .NET BCL usually calls IFormattable.
To S t r i n g ( ) w i t h a n u l l f o r m a t s t r i n g , b u t a f e w l o c a t i o n s u s e t h e " G " f o r m a t
string to indicate the general format. If you add support for the IFormattable
interface and do not support these standard formats, you've broken the
automatic string conversions in the BCL. You can see that supporting
IFormattable can quickly get out of hand. You can't anticipate all the pos-
sible format options that your type might support. At most, pick a few of
the most likely formats. Client code should make up all the edge cases.
The second parameter to IFormattable.ToString() is an object that imple-
ments the IFormatProvider interface. This object lets clients provide for-
matting options that you did not anticipate. If you look at the previous
implementation of IFormattable.ToString(), you will undoubtedly come
up with any number of format options that you would like but that you
find lacking. That's the nature of providing human-readable output. No
matter how many different formats you support, your users will one day
want some format that you did not anticipate. That's why the first few lines
of the method look for an object that implements IFormatProvider and
delegate the job to its ICustomFormatter.
Shift your focus now from class author to class consumer. You find that
you want a format that is not supported. For example, you have customers
 
Search WWH ::




Custom Search