Updated: February 2009
Provides a mechanism for retrieving an object to control formatting.
<ComVisibleAttribute(True)> _ Public Interface IFormatProvider
Dim instance As IFormatProvider
[ComVisibleAttribute(true)] public interface IFormatProvider
[ComVisibleAttribute(true)] public interface class IFormatProvider
public interface IFormatProvider
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, array<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 NumberFormatInfo class, which provides information that is used to format numbers, such as the currency, thousands separator, and decimal separator symbols for a particular culture.
The DateTimeFormatInfo class, which provides information that is used to format dates and times, such as the date and time separator symbols for a particular culture or the order and form of a date's year, month, and day components.
The CultureInfo class, which represents a particular culture. Its GetFormat method returns a culture-specific NumberFormatInfo or DateTimeFormatInfo object, depending on whether the CultureInfo object is used in a formatting or parsing operation that involves numbers or dates and times.
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, array<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
using System; using System.Globalization; public class Example { public static void Main() { DateTime dateValue = new DateTime(2009, 6, 1, 4, 37, 0); CultureInfo[] cultures = { new CultureInfo("en-US"), new CultureInfo("fr-FR"), new CultureInfo("it-IT"), new CultureInfo("de-DE") }; foreach (CultureInfo culture in cultures) Console.WriteLine("{0}: {1}", culture.Name, dateValue.ToString(culture)); } } // 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 nullNothingnullptra null reference (Nothing in Visual Basic).
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 ' 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) ' Support G and H format specifiers. If String.IsNullOrEmpty(fmt) Then fmt = "G" If fmt.ToUpper = "G" Return result ' Add hyphens for H format specifier. Else If fmt.ToUpper = "H" Return Left(result, 5) & "-" & Mid(result, 6, 3) & "-" & Right(result, 4) ' Throw an exception for any other format specifier. Else Throw New FormatException(String.Format("{0} is not a valid format string.", fmt)) End If End Function End Class
public class AcctNumberFormat : IFormatProvider, ICustomFormatter { private const int ACCT_LENGTH = 12; public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; else return null; } public string Format(string fmt, object arg, IFormatProvider formatProvider) { // Convert argument to a string. string result = arg.ToString(); // If account number is less than 12 characters, pad with leading zeroes. if (result.Length < ACCT_LENGTH) result = result.PadLeft(ACCT_LENGTH, '0'); // If account number is more than 12 characters, truncate to 12 characters. if (result.Length > ACCT_LENGTH) result = result.Substring(0, ACCT_LENGTH); // Support G and H format specifiers. if (String.IsNullOrEmpty(fmt)) fmt = "G"; if (fmt.ToUpper() == "G") return result; // Add hyphens for H format specifier. else if (fmt.ToUpper() == "H") return result.Substring(0, 5) + "-" + result.Substring(5, 3) + "-" + result.Substring(8); // Return string representation of argument for any other formatting code. else throw new FormatException(String.Format("{0} is not a valid format string.", fmt)); } }
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, array<Object>[]()[]) method to generate a string that contains a formatted 12-digit account number.
Module TestFormatting Public Sub Main() Dim acctNumber As Long acctNumber = 104254567890 Console.WriteLine(String.Format(New AcctNumberFormat, "{0:H}", acctNumber)) Console.WriteLine(String.Format(New AcctNumberFormat, "{0}", acctNumber)) acctNumber = 14567890 Console.WriteLine(String.Format(New AcctNumberFormat, "{0:H}", acctNumber)) Console.WriteLine(String.Format(New AcctNumberFormat, "{0}", acctNumber)) acctNumber = 18779887654111 Console.WriteLine(String.Format(New AcctNumberFormat, "{0:H}", acctNumber)) Console.WriteLine(String.Format(New AcctNumberFormat, "{0}", acctNumber)) End Sub End Module ' The example displays the following output: ' 10425-456-7890 ' 104254567890 ' 00001-456-7890 ' 000014567890 ' 18779-887-6541 ' 187798876541
public class TestFormatting { public static void Main() { long acctNumber; acctNumber = 104254567890; Console.WriteLine(String.Format(new AcctNumberFormat(), "{0:H}", acctNumber)); Console.WriteLine(String.Format(new AcctNumberFormat(), "{0}", acctNumber)); acctNumber = 14567890; Console.WriteLine(String.Format(new AcctNumberFormat(), "{0:H}", acctNumber)); Console.WriteLine(String.Format(new AcctNumberFormat(), "{0}", acctNumber)); acctNumber = 18779887654111; Console.WriteLine(String.Format(new AcctNumberFormat(), "{0:H}", acctNumber)); Console.WriteLine(String.Format(new AcctNumberFormat(), "{0}", acctNumber)); } } // The example displays the following output: // 10425-456-7890 // 104254567890 // 00001-456-7890 // 000014567890 // 18779-887-6541 // 187798876541
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
Date
History
Reason
February 2009
Expanded the Remarks section and added another example.
Customer feedback.