
Adding Custom Format Strings for Custom Types
If you create your own custom type, you can add support for processing your own custom format strings by implementing the IFormattable interface and that interface's ToString method. This means you can control what format strings are recognized by your custom type. The benefit of implementing the IFormattable interface instead of merely adding a ToString method to your custom type is that you can guarantee users of your ToString method a predefined calling syntax and return type.
The ToString method of the IFormattable interface takes a format string parameter and a format provider parameter. If the format string parameter is an empty string or null (Nothing in Visual Basic), perform default formatting. If the format provider is null, use a default format provider.
If a custom format string is passed to your custom version of ToString, perform the appropriate formatting; otherwise, call a suitable .NET Framework method to perform standard formatting.
In the following example, the MyType custom type implements the IFormattable interface. If you create a new instance of the MyType class, and pass the "b" custom format string to the instance's ToString method, an overload of Convert.ToString returns the binary (base 2) string representation of the value of the instance. If "b" is not passed, the value of the instance is formatted by its own ToString method; that is, integer myValue is formatted by the System.Int32.ToString method.
Public Class MyType
Implements IFormattable
' Assign a value for the class.
Private myValue As Integer
' Add a constructor.
Public Sub New(value As Integer)
myValue = value
End Sub
' Write a custom Format method for the type.
Public Overloads Function ToString(format As String, _
fp As IFormatProvider) As String _
Implements IFormattable.ToString
If format.Equals("b") Then
Return Convert.ToString(myValue, 2)
Else
Return myValue.ToString(format, fp)
End If
End Function
End Class
public class MyType : IFormattable
{
// Assign a value for the class.
private int myValue;
// Add a constructor.
public MyType( int value )
{
myValue = value;
}
// Write a custom Format method for the type.
public string ToString(string format, IFormatProvider fp)
{
if (format.Equals ("b"))
{
return Convert.ToString (myValue, 2);
}
else
{
return myValue.ToString(format, fp);
}
}
}
The following example demonstrates how the MyType class and "b" format string are used.
Dim mtype As New MyType(42)
Dim myString As String = mtype.ToString("b", Nothing)
Dim yourString As String = mtype.ToString("d", Nothing)
Console.WriteLine(myString)
Console.WriteLine(yourString)
' The example produces the following output:
' 101010
' 42
MyType mtype = new MyType(42);
String myString = mtype.ToString("b", null);
String yourString = mtype.ToString("d", null);
Console.WriteLine(myString);
Console.WriteLine(yourString);
// The example produces the following output:
// 101010
// 42