Information Technology Reference
In-Depth Information
The previous customer type has three fields: the name, the revenue, and a
contact phone. The System.ToString() override uses only the name. You
can address that deficiency by implementing the IFormattable interface
on your type. IFormattable contains an overloaded ToString() method that
lets you specify formatting information for your type. It's the interface you
use when you need to create different forms of string output. The cus-
tomer class is one of those instances. Users will want to create a report that
contains the customer name and last year's revenue in a tabular format.
The IFormattable.ToString() method provides the means for you to let
users format string output from your type. The IFormattable.ToString()
method signature contains a format string and a format provider:
string System. IFormattable .ToString( string format,
IFormatProvider formatProvider)
Yo u c a n u s e t h e f o r m a t s t r i n g t o s p e c i f y y o u r o w n f o r m a t s f o r t h e t y p e s
you create. You can specify your own key characters for the format strings.
In the customer example, you could specify n to mean the name, r for the
revenue, and p for the phone. By allowing the user to specify combina-
tions as well, you would create this version of IFormattable.ToString():
// supported formats:
// substitute n for name.
// substitute r for revenue
// substitute p for contact phone.
// Combos are supported: nr, np, npr, etc
// "G" is general.
string System. IFormattable .ToString( string format,
IFormatProvider formatProvider)
{
if (formatProvider != null )
{
ICustomFormatter fmt = formatProvider.GetFormat(
this .GetType())
as ICustomFormatter ;
if (fmt != null )
return fmt.Format(format, this , formatProvider);
}
switch (format)
{
 
Search WWH ::




Custom Search