Format Method
Collapse the table of content
Expand the table of content

ICustomFormatter.Format Method

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Converts the value of a specified object to an equivalent string representation using specified format and culture-specific formatting information.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Function Format ( _
	format As String, _
	arg As Object, _
	formatProvider As IFormatProvider _
) As String

Parameters

format
Type: System.String
A format string containing formatting specifications.
arg
Type: System.Object
An object to format.
formatProvider
Type: System.IFormatProvider
An IFormatProvider object that supplies format information about the current instance.

Return Value

Type: System.String
The string representation of the value of arg, formatted as specified by format and formatProvider.

ICustomFormatter.Format is a callback method. It is called by a method that supports custom formatting, such as String.Format(IFormatProvider, String, Object()). The implementation is called once for each format item in a Composite Formatting. For example, in the following statement, the ICustomFormatter.Format method is called three times.


outputBlock.Text &= String.Format(New BinaryFormatter(), _
                                "{0} (binary: {0:B}) (hex: {0:H})", byteValue) & vbCrLf


The arg parameter is the object in the object list whose zero-based position corresponds to the index of a particular format item.

The format parameter contains a format string, which is the formatString component of a format item. If the format item has no formatString component, the value of format is Nothing. If format is Nothing, depending on the type of arg, you may be able to use the default format specification of your choice.

The formatProvider parameter is the IFormatProvider implementation that provides formatting for arg. Typically, it is an instance of your ICustomFormatter implementation. If formatProvider is Nothing, ignore that parameter.

Your implementation of the 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. The following code illustrates this pattern.


If TypeOf arg Is IFormattable Then
   Return DirectCast(arg, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
ElseIf arg IsNot Nothing Then
   Return arg.ToString()


The following example implements ICustomFormatter to allow binary, octal, and hexadecimal formatting of integral values. 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

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))                  
      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 Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim byteValue As Byte = 124
      outputBlock.Text &= String.Format(New BinaryFormatter(), _
                                      "{0} (binary: {0:B}) (hex: {0:H})", byteValue) & vbCrLf

      Dim intValue As Integer = 23045
      outputBlock.Text &= String.Format(New BinaryFormatter(), _
                                      "{0} (binary: {0:B}) (hex: {0:H})", intValue) + vbCrLf

      Dim ulngValue As ULong = 31906574882
      outputBlock.Text &= String.Format(New BinaryFormatter(), _
                                      "{0} {1}   (binary: {0:B}) {1}   (hex: {0:H}){1}", _
                                      ulngValue, 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)


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2017 Microsoft