Customizing the Format Method for Custom Types
You can easily implement a Format method for your own custom types by overriding the IFormattable Interface. All .NET Framework numeric base types implement IFormattable and have overridden the Format method of that class. In the overridden Format method you can either handle the built-in codes yourself, catch custom codes, or pass codes on to the IFormattable object.
The IFormattable interface combined with the IServiceProvider interface provides the following functionality:
Conversion of numbers, dates and times to strings using a built-in set of specifiers called formatting codes.
Extensibility through overriding of the IServiceProvider object allowing you to extend the format codes offered for base types.
Enhancement of custom types by allowing existing and custom codes to be applied through the Format method.
The following example illustrates the creation of a custom type called MyType. This example adds a custom format specifier of B that will return a binary representation of the type's value.
public class MyType : IFormattable
{
// a value for our class
private int MyValue;
// constructor
public MyType( int value )
{
MyValuealue = value;
}
//Custom Format method for the type
public string Format(string format, IServiceObjectProvider sop)
{
if (format.Equals ("b"))
{
return Convert.ToString (MyValue, 2);
}
else {
return MyValue.Format (format, sop);
}
}
}
Customizing the Format method for existing types
By overriding IServiceObjectProvider and ICustomFormatter you can provide additional codes for formatting base types in an already defined class. First, you define a class that implements the two previous mentioned interfaces and overrides GetServiceObject and Format. The following code defines a class that adds a custom Format method that can produce different base-values of an integer:
public class MyFormat : IServiceObjectProvider, ICustomFormatter
{
//String.Format calls this method to get an instance of a
//ICustomFormatter to handle the formatting.
public object GetServiceObject (Type service)
{
if (service == typeof (ICustomFormatter))
{
return this;
}
else{
return null;
}
}
//Once String.Format gets the ICustomFormatter it calls this format
//method on each argument.
public string Format (string format, object arg, IServiceObjectProvider sop)
{
if (format == null