Export (0) Print
Expand All
2 out of 3 rated this helpful - Rate this topic

ICustomFormatter Interface

Defines a method that supports custom formatting of the value of an object.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
'Declaration
<ComVisibleAttribute(True)> _
Public Interface ICustomFormatter

The ICustomFormatter type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryFormatConverts the value of a specified object to an equivalent string representation using specified format and culture-specific formatting information.
Top

The ICustomFormatter interface includes a single method, ICustomFormatter.Format. When this interface is implemented by a reference or value type, the Format method returns a custom-formatted string representation of an object's value.

Typically, the ICustomFormatter interface is implemented with the IFormatProvider interface to customize the behavior of .NET Framework string formatting methods that include an IFormatProvider parameter. For example, the ICustomFormatter interface can provide custom formatting of the value of an object passed to the String.Format(IFormatProvider, String, Object()) method.

Providing a custom representation of an object's value requires that you do the following:

  1. Define a class that implements the ICustomFormatter interface and its single member, the Format method.

  2. Define a class that implements the IFormatProvider interface and its single member, the GetFormat method. The GetFormat method returns an instance of your ICustomFormatter implementation. Often, a single class implements both ICustomFormatter and IFormatProvider. In that case, the class's GetFormat implementation just returns an instance of itself.

  3. Pass the IFormatProvider implementation as the provider argument of the String.Format(IFormatProvider, String, Object()) method or a comparable method.

The .NET Framework method will then use your custom formatting instead of its own.

Notes to Implementers

The common language runtime attempts to use your ICustomFormatter implementation for every format item in a composite format string. As a result, you should expect that your ICustomFormatter implementation will be called to provide formatting services to objects or values that it is not designed to handle. In these cases, your Format method must call the appropriate formatting method for that object or value.

There are two kinds of ICustomFormatter implementations: intrinsic and extension.

Intrinsic implementations are implementations that provide custom formatting for an application-defined object. In this case, your implementation should include the following:

  • A definition of format strings that define the formatting of the object. Format strings are optional. Typically, a "G" or "g" format string defines the general (or most commonly used) format. However, you are free to define any format strings that you choose. You are also free to decide whether they are case-sensitive or case-insensitive.

  • A test to ensure that the type of the object passed to your Format method is your application-defined type. If it is not, you should call the object's IFormattable implementation, if one exists, or its ToString method, if it does not. You should be prepared to handle any exceptions these method calls might throw.

  • Code to handle a null format string, if your implementation supports format strings. The most common approach is to replace a null format string with the general format specifier.

  • Code to handle any format strings that your implementation supports.

  • Code to handle format strings that you do not support. The most common approach is to throw a FormatException, although you can provide default formatting.

Extension implementations are implementations that provide custom formatting for a type that already has formatting support. For example, you could define a CustomerNumberFormatter that formats an integral type with hyphens between specific digits. In this case, your implementation should include the following:

  • A definition of format strings that extend the formatting of the object. These format strings are required, but they must not conflict with the type's existing format strings. For example, if you are extending formatting for the Int32 type, you should not implement the "C", "D", "E", "F", and "G" format specifiers, among others.

  • A test that the type of the object passed to your Format method is a type whose formatting your extension supports. If it is not, call the object's IFormattable implementation, if one exists, or the object's parameterless ToString method, if it does not. You should be prepared to handle any exceptions these method calls might throw.

  • Code to handle any format strings that your extension supports.

  • Code to handle any format strings that your extension does not support. These should be passed on to the type's IFormattable implementation. You should be prepared to handle any exceptions these method calls might throw.

The following example implements ICustomFormatter to allow binary, octal, and hexadecimal formatting of integral values. In this example, a single class, IBinaryFormatter, implements both ICustomFormatter and IFormatProvider. Its IFormatProvider.GetFormat method determines whether the formatType parameter represents an ICustomFormatter type. If it does, BinaryFormatter returns an instance of itself; otherwise, it returns Nothing. Its ICustomFormatter.Format implementation determines whether the format parameter is one of the three supported format strings ("B" for binary, "O" for octal, and "H" for hexadecimal) and formats the arg parameter appropriately. Otherwise, if arg is not Nothing, it calls the arg parameter's IFormattable.ToString implementation, if one exists, or its parameterless ToString method, if one does not. If arg is Nothing, the method returns String.Empty.


Imports System.Globalization
Imports System.Numerics

Public Class BinaryFormatter : Implements IFormatProvider, ICustomFormatter
   ' IFormatProvider.GetFormat implementation.
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      ' Determine whether custom formatting object is requested.
      If formatType Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If
   End Function   

   ' Format number in binary (B), octal (O), or hexadecimal (H).
   Public Function Format(fmt As String, arg As Object, _
                          formatProvider As IFormatProvider) As String _
                   Implements ICustomFormatter.Format

     ' Handle format string.
      Dim base As Integer
      ' Handle null or empty format string, string with precision specifier.
      Dim thisFmt As String = String.Empty
      ' Extract first character of format string (precision specifiers
      ' are not supported by BinaryFormatter).
      If Not String.IsNullOrEmpty(fmt) Then
         thisFmt = CStr(IIf(fmt.Length > 1, fmt.Substring(0, 1), fmt))
      End If



      ' Get a byte array representing the numeric value.
      Dim bytes() As Byte
      If TypeOf(arg) Is SByte Then
         Dim byteString As String = CType(arg, SByte).ToString("X2")
         bytes = New Byte(0) { Byte.Parse(byteString, System.Globalization.NumberStyles.HexNumber ) }
      ElseIf TypeOf(arg) Is Byte Then
         bytes = New Byte(0) { CType(arg, Byte) }
      ElseIf TypeOf(arg) Is Int16 Then
         bytes = BitConverter.GetBytes(CType(arg, Int16))
      ElseIf TypeOf(arg) Is Int32 Then
         bytes = BitConverter.GetBytes(CType(arg, Int32))
      ElseIf TypeOf(arg) Is Int64 Then
         bytes = BitConverter.GetBytes(CType(arg, Int64))
      ElseIf TypeOf(arg) Is UInt16 Then
         bytes = BitConverter.GetBytes(CType(arg, UInt16))
      ElseIf TypeOf(arg) Is UInt32 Then
         bytes = BitConverter.GetBytes(CType(arg, UInt64))
      ElseIf TypeOf(arg) Is UInt64 Then
         bytes = BitConverter.GetBytes(CType(arg, UInt64))                  
      ElseIf TypeOf(arg) Is BigInteger Then
         bytes = CType(arg, BigInteger).ToByteArray()
      Else
         Try 
            Return HandleOtherFormats(fmt, arg) 
         Catch e As FormatException 
            Throw New FormatException(String.Format("The format of '{0}' is invalid.", fmt), e)
         End Try
      End If

      Select Case thisFmt.ToUpper()
         ' Binary formatting.
         Case "B"
            base = 2        
         Case "O"
            base = 8
         Case "H"
            base = 16
         ' Handle unsupported format strings.
         Case Else
            Try 
               Return HandleOtherFormats(fmt, arg) 
            Catch e As FormatException 
               Throw New FormatException(String.Format("The format of '{0}' is invalid.", fmt), e)
            End Try
      End Select

      ' Return a formatted string.
      Dim numericString As String = String.Empty
      For ctr As Integer = bytes.GetUpperBound(0) To bytes.GetLowerBound(0) Step -1
         Dim byteString As String = Convert.ToString(bytes(ctr), base)
         If base = 2 Then
            byteString = New String("0"c, 8 - byteString.Length) + byteString
         ElseIf base = 8 Then
            byteString = New String("0"c, 4 - byteString.Length) + byteString
         ' Base is 16.
         Else     
            byteString = New String("0"c, 2 - byteString.Length) + byteString
         End If
         numericString +=  byteString + " "
      Next
      Return numericString.Trim()
   End Function

   Private Function HandleOtherFormats(fmt As String, arg As Object) As String
      If TypeOf arg Is IFormattable Then
         Return DirectCast(arg, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
      ElseIf arg IsNot Nothing Then
         Return arg.ToString()
      Else
         Return String.Empty
      End If
   End Function
End Class


BinaryFormatter can then be used to provide custom formatting by passing a BinaryFormatter object as the provider parameter of the Format method, as the following example shows.


Public Module Example
   Public Sub Main
      Console.WindowWidth = 100

      Dim byteValue As Byte = 124
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} (binary: {0:B}) (hex: {0:H})", byteValue))

      Dim intValue As Integer = 23045
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} (binary: {0:B}) (hex: {0:H})", intValue))

      Dim ulngValue As ULong = 31906574882
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} {1}   (binary: {0:B}) {1}   (hex: {0:H})", _
                                      ulngValue, vbCrLf))

      Dim bigIntValue As BigInteger = BigInteger.Multiply(Int64.MaxValue, 2)
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} {1}   (binary: {0:B}) {1}   (hex: {0:H})", _
                                      bigIntValue, vbCrLf))
   End Sub
End Module
' The example displays the following output:
'    124 (binary: 01111100) (hex: 7c)
'    23045 (binary: 00000000 00000000 01011010 00000101) (hex: 00 00 5a 05)
'    31906574882
'       (binary: 00000000 00000000 00000000 00000111 01101101 11000111 10110010 00100010)
'       (hex: 00 00 00 07 6d c7 b2 22)
'    18446744073709551614
'       (binary: 00000000 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111110)
'       (hex: 00 ff ff ff ff ff ff ff fe)


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.