ICustomFormatter
ICustomFormatter is an interface that allows you to replace or extend a built-in or already
existing IFormattable interface for an object. Whenever you call String.Format() or
StringBuilder.AppendFormat() to convert an object instance to a string, before the method
calls through to the object??™s implementation of IFormattable.ToString(), it first checks to
see if the passed-in IFormatProvider provides a custom formatter. It does this by calling
IFormatProvider.GetFormat() while passing a type of ICustomFormatter. If the formatter
returns an implementation of ICustomFormatter, then the method will use the custom
formatter. Otherwise, it will use the object??™s implementation of IFormattable.ToString()
or the object??™s implementation of Object.ToString() in cases where it doesn??™t implement
IFormattable.
Consider the following example where we??™ve reworked the previous Complex example but
externalized the debugging output capabilities outside of the Complex structure:
Imports System
Imports System.Text
Imports System.Globalization
CHAPTER 9 n WORKING WITH STRINGS 177
Public Class ComplexDbgFormatter
Implements ICustomFormatter
Implements IFormatProvider
'IFormatProvider implementation
Public Function GetFormat(ByVal formatType As Type) As Object _
Implements System.
Pages:
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300