public interface ICustomFormatter
|
Use this interface, and the IFormatProvider interface, to supersede the support supplied in .NET Framework formatting methods that honor an IFormatProvider parameter. For example, use this interface to provide custom formatting of the value of an object by the String.Format or Int32.ToString methods.
Derive a class that implements the IFormatProvider interface and its IFormatProvider.GetFormat method. Specify that derived class for the IFormatProvider parameter of the method you want to supersede. Your implementation of the IFormatProvider.GetFormat method should return a format object that implements the ICustomFormatter interface. The .NET Framework method will then use your custom formatting instead of its own.
Format | Converts the value of a specified object to an equivalent string representation using specified format and culture-specific formatting information. |
string Format(string format, object arg, I Format( |
format
arg
formatProvider
Exception Type | Condition |
---|---|
ArgumentNullException | arg is null. |
Throw an exception only if arg is null. If format is null, use the default format specification of your choice. If formatProvider is null, ignore that parameter.
Your implementation of the ICustomFormatter.Format method must include the following functionality so the .NET Framework can provide formatting you do not support. If your format method does not support a format, determine whether the object being formatted implements the IFormattable interface. If it does, invoke the IFormattable.ToString method of that interface. Otherwise, invoke the default Object.ToString method of the underlying object.
Here is a fragment of C# code that demonstrates this pattern for object arg, format format, format provider formatProvider, and return value, s.
if (arg is IFormattable) s = ((IFormattable)arg).ToString(format, formatProvider);
else if (arg != null) s = arg.ToString();