Export (0) Print
Expand All

IFormatProvider Interface

Provides a mechanism for retrieving an object to control formatting.

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

'Declaration
<ComVisibleAttribute(True)> _
Public Interface IFormatProvider

The IFormatProvider type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetFormatReturns an object that provides formatting services for the specified type.
Top

The IFormatProvider interface supplies an object that provides formatting information for formatting and parsing operations. Formatting operations convert the value of a type to the string representation of that value. Typical formatting methods are the ToString methods of a type, as well as Format. Parsing operations convert the string representation of a value to a type with that value. Typical parsing methods are Parse and TryParse.

The IFormatProvider interface consists of a single method, IFormatProvider.GetFormat. GetFormat is a callback method: The parsing or formatting method calls it and passes it a Type object that represents the type of object that the formatting or parsing method expects will provide formatting information. The GetFormat method is responsible for returning an object of that type.

IFormatProvider implementations are often used implicitly by formatting and parsing methods. For example, the DateTime.ToString(String) method implicitly uses an IFormatProvider implementation that represents the system's current culture. IFormatProvider implementations can also be specified explicitly by methods that have a parameter of type IFormatProvider, such as Int32.Parse(String, IFormatProvider) and String.Format(IFormatProvider, String, Object()).

The .NET Framework includes the following three predefined IFormatProvider implementations to provide culture-specific information that is used in formatting or parsing numeric and date and time values:

The .NET Framework also supports custom formatting. This typically involves the creation of a formatting class that implements both IFormatProvider and ICustomFormatter. An instance of this class is then passed as a parameter to a method that performs a custom formatting operation, such as String.Format(IFormatProvider, String, Object()) The example provides an illustration of such a custom implementation that formats a number as a 12-digit account number.

The following example illustrates how an IFormatProvider implementation can change the representation of a date and time value. In this case, a single date is displayed by using CultureInfo objects that represent four different cultures.

Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateValue As Date = #06/01/2009 4:37PM#
      Dim cultures() As CultureInfo = {New CultureInfo("en-US"), _
                                       New CultureInfo("fr-FR"), _
                                       New CultureInfo("it-IT"), _
                                       New CultureInfo("de-DE") }
      For Each culture As CultureInfo In cultures
         Console.WriteLine("{0}: {1}", culture.Name, dateValue.ToString(culture))
      Next                                         
   End Sub 
End Module 
' The example displays the following output: 
'       en-US: 6/1/2009 4:37:00 PM 
'       fr-FR: 01/06/2009 16:37:00 
'       it-IT: 01/06/2009 16.37.00 
'       de-DE: 01.06.2009 16:37:00

The following example illustrates the use of a class that implements the IFormatProvider interface and the GetFormat method. The AcctNumberFormat class converts an Int64 value that represents an account number to a formatted 12-digit account number. Its GetFormat method returns a reference to the current AcctNumberFormat instance if the formatType parameter refers to a class that implements ICustomFormatter; otherwise, GetFormat returns Nothing.

Public Class AcctNumberFormat : Implements IFormatProvider, ICustomFormatter

   Private Const ACCT_LENGTH As Integer = 12

   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      If formatType Is GetType(ICustomFormatter) Then 
         Return Me 
      Else 
         Return Nothing 
      End If 
   End Function 

   Public Function Format(fmt As String, arg As Object, formatProvider As IFormatProvider) As String _
                          Implements ICustomFormatter.Format

      ' Provide default formatting if arg is not an Int64. 
       If Not TypeOf arg Is Int64 Then 
         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    

      ' Provider default formatting for unsupported format strings. 
      Dim ufmt As String = fmt.ToUpper(CultureInfo.InvariantCulture)
      If Not (ufmt = "H" Or ufmt = "I") Then 
         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    

      ' Convert argument to a string. 
      Dim result As String = arg.ToString()

      ' If account number is less than 12 characters, pad with leading zeroes. 
      If result.Length < ACCT_LENGTH Then result = result.PadLeft(ACCT_LENGTH, "0"c)
      ' If account number is more than 12 characters, truncate to 12 characters. 
      If result.Length > ACCT_LENGTH Then result = Left(result, ACCT_LENGTH)   

      If ufmt = "I"                              ' Integer-only format.
         Return result
      ' Add hyphens for H format specifier. 
      Else                                       ' Hypenated format.
         Return Left(result, 5) & "-" & Mid(result, 6, 3) & "-" & Right(result, 4)
      End If    
   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

The class that implements IFormatProvider can then be used in a call to a formatting and parsing operation. For example, the following code calls the String.Format(IFormatProvider, String, Object()) method to generate a string that contains a formatted 12-digit account number.

Imports System.Globalization

Public Enum DaysOfWeek As Long
   Monday = 1
   Tuesday = 2
End Enum 

Module TestFormatting
   Public Sub Main()
      Dim acctNumber As Long, balance As Double  
      Dim wday As DaysOfWeek 
      Dim output As String

      acctNumber = 104254567890
      balance = 16.34
      wday = DaysOfWeek.Monday

      output = String.Format(New AcctNumberFormat(), "On {2}, the balance of account {0:H} was {1:C2}.", acctNumber, balance, wday)
      Console.WriteLine(output)

      wday = DaysOfWeek.Tuesday
      output = String.Format(New AcctNumberFormat(), "On {2}, the balance of account {0:I} was {1:C2}.", acctNumber, balance, wday)
      Console.WriteLine(output)
   End Sub 
End Module 
' The example displays the following output: 
'    On Monday, the balance of account 10425-456-7890 was $16.34. 
'    On Tuesday, the balance of account 104254567890 was $16.34.

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 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

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft