Udostępnij za pośrednictwem


String.Format Method (IFormatProvider, String, array<Object[])

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Replaces the format item in a specified string with the text equivalent of the value of a corresponding object in a specified array. A specified parameter supplies culture-specific formatting information.

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

Syntax

'Declaration
Public Shared Function Format ( _
    provider As IFormatProvider, _
    format As String, _
    ParamArray args As Object() _
) As String
public static string Format(
    IFormatProvider provider,
    string format,
    params Object[] args
)

Parameters

  • format
    Type: System.String
    A composite format string (see Remarks).
  • args
    Type: array<System.Object[]
    An object array that contains zero or more objects to format.

Return Value

Type: System.String
A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.

Exceptions

Exception Condition
ArgumentNullException

format or args is nulla null reference (Nothing in Visual Basic).

FormatException

format is invalid.

-or-

The index of a format item is less than zero, or greater than or equal to the length of the args array.

Remarks

This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its string representation and to embed that representation in a string. The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics.

The provider parameter supplies custom and culture-specific information used to moderate the formatting process. The provider parameter is an IFormatProvider implementation whose GetFormat method is called by the String.Format(IFormatProvider, String, array<Object[]) method. The method must return an object to supply formatting information that is of the same type as the formatType parameter. The provider parameter's GetFormat method is called one or more times, depending on the specific type of objects in args, as follows:

  • It is always passed a Type object that represents the ICustomFormatter type.

  • It is passed a Type object that represents the DateTimeFormatInfo type for each format item whose corresponding data type is a date and time value.

  • It is passed a Type object that represents the NumberFormatInfo type for each format item whose corresponding data type is numeric.

For more information, see the Format Providers section of the Formatting Types topic. The Example section provides an example of a custom format provider that outputs numeric values as customer account numbers with embedded hyphens.

The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. The formatting process replaces each format item with the string representation of the corresponding object.

The syntax of a format item is as follows:

{index[,length][:formatString]}

Elements in square brackets are optional. The following table describes each element. For more information about the composite formatting feature, including the syntax of a format item, see Composite Formatting.

Element

Description

index

The zero-based position in the parameter list of the object to be formatted. If there is no parameter in the index position, a FormatException is thrown. If the object specified by index is nulla null reference (Nothing in Visual Basic), the format item is replaced by String.Empty.

,length

The minimum number of characters in the string representation of the object to be formatted. If positive, the object to be formatted is right-aligned; if negative, it is left-aligned. The comma is required if length is specified.

:formatString

A standard or custom format string that is supported by the object to be formatted. Possible values for formatString are the same as the values supported by the object's ToString(format) method. If formatString is not specified and the object to be formatted implements the IFormattable interface, nulla null reference (Nothing in Visual Basic) is passed as the value of the format parameter used as the IFormattable.ToString format string.

NoteNote:

For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. For the standard format strings used with enumerations, see Enumeration Format Strings.

The leading and trailing brace characters, '{' and '}', are required. To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".

If the value of format is, "Thank you for your purchase of {0:####} copies of Microsoft®.NET (Core Reference).", and arg[0] is an Int16 with the value 123, then the return value will be:

"Thank you for your purchase of 123 copies of Microsoft®.NET (Core Reference)."

If the value of format is, "Brad's dog has {0,-8:G} fleas.", arg[0]is an Int16 with the value 42, (and in this example, underscores represent padding spaces) then the return value will be:

"Brad's dog has 42______ fleas."

Examples

The following example uses the String.Format(IFormatProvider, String, array<Object[]) method to display the string representation of some date and time and numeric values using several different cultures.

Imports System.Globalization
Imports System.Windows.Media

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      outputBlock.FontFamily = New FontFamily("Courier New")

      Dim cultureNames() As String = {"en-US", "fr-FR", "de-DE", "es-ES"}

      Dim dateToDisplay As Date = #9/1/2009 6:32:00 PM#
      Dim value As Double = 9164.32

      outputBlock.Text &= "Culture     Date                                Value" & vbCrLf
      outputBlock.Text &= vbCrLf
      For Each cultureName As String In cultureNames
         Dim culture As New CultureInfo(cultureName)
         Dim output As String = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", _
                                              culture.Name, dateToDisplay, value)
         outputBlock.Text &= output & vbCrLf
      Next
   End Sub
End Module
' The example displays the following output:
'       Culture     Date                                Value
'       
'       en-US       Tuesday, September 01, 2009         9,164.32
'       fr-FR       mardi 1 septembre 2009              9 164,32
'       de-DE       Dienstag, 1. September 2009         9.164,32
'       es-ES       martes, 01 de septiembre de 2009    9.164,32
using System;
using System.Globalization;
using System.Windows.Media;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      outputBlock.FontFamily = new FontFamily("Courier New");

      string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };

      DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
      double value = 9164.32;

      outputBlock.Text += "Culture     Date                                Value\n" + "\n";
      foreach (string cultureName in cultureNames)
      {
         CultureInfo culture = new CultureInfo(cultureName);
         string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}",
                                       culture.Name, dateToDisplay, value);
         outputBlock.Text += output + "\n";
      }
   }
}
// The example displays the following output:
//    Culture     Date                                Value
//    
//    en-US       Tuesday, September 01, 2009         9,164.32
//    fr-FR       mardi 1 septembre 2009              9 164,32
//    de-DE       Dienstag, 1. September 2009         9.164,32
//    es-ES       martes, 01 de septiembre de 2009    9.164,32

The following example defines a customer number format provider that formats an integer value as a customer account number in the form x-xxxxx-xx.

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim acctNumber As Integer = 79203159
      outputBlock.Text += String.Format(New CustomerFormatter, "{0}", acctNumber) & vbCrLf
      outputBlock.Text += String.Format(New CustomerFormatter, "{0:G}", acctNumber) & vbCrLf
      outputBlock.Text += String.Format(New CustomerFormatter, "{0:S}", acctNumber) & vbCrLf
      outputBlock.Text += String.Format(New CustomerFormatter, "{0:P}", acctNumber) & vbCrLf
      Try
         outputBlock.Text += String.Format(New CustomerFormatter, "{0:X}", acctNumber) & vbCrLf
      Catch e As FormatException
         outputBlock.Text += e.Message + vbCrLf
      End Try   
   End Sub
End Module

Public Class CustomerFormatter : Implements IFormatProvider, ICustomFormatter
   Public Function GetFormat(ByVal type As Type) As Object _
                   Implements IFormatProvider.GetFormat
      If type Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If
   End Function

   Public Function Format(ByVal fmt As String, _
                        ByVal arg As Object, _
                        ByVal formatProvider As IFormatProvider) As String _
                 Implements ICustomFormatter.Format
      If Not Me.Equals(formatProvider) Then
         Return Nothing
      Else
         If String.IsNullOrEmpty(fmt) Then fmt = "G"

         Dim customerString As String = arg.ToString()
         If customerString.Length < 8 Then _
            customerString = customerString.PadLeft(8, "0"c)

         Select Case fmt
            Case "G"
               Return customerString.Substring(0, 1) & "-" & _
                                customerString.Substring(1, 5) & "-" & _
                                customerString.Substring(6)
            Case "S"
               Return customerString.Substring(0, 1) & "/" & _
                                customerString.Substring(1, 5) & "/" & _
                                customerString.Substring(6)
            Case "P"
               Return customerString.Substring(0, 1) & "." & _
                                customerString.Substring(1, 5) & "." & _
                                customerString.Substring(6)
            Case Else
               Throw New FormatException( _
                         String.Format("The '{0}' format specifier is not supported.", fmt))
         End Select
      End If
   End Function
End Class
' The example displays the following output:
'       7-92031-59
'       7-92031-59
'       7/92031/59
'       7.92031.59
'       The 'X' format specifier is not supported.
using System;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      int acctNumber = 79203159;
      outputBlock.Text += String.Format(new CustomerFormatter(), "{0}", acctNumber) + "\n";
      outputBlock.Text += String.Format(new CustomerFormatter(), "{0:G}", acctNumber) + "\n";
      outputBlock.Text += String.Format(new CustomerFormatter(), "{0:S}", acctNumber) + "\n";
      outputBlock.Text += String.Format(new CustomerFormatter(), "{0:P}", acctNumber) + "\n";
      try {
         outputBlock.Text += String.Format(new CustomerFormatter(), "{0:X}", acctNumber) + "\n";
      }
      catch (FormatException e) {
         outputBlock.Text += e.Message + "\n";
      }
   }
}

public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string format,
                          object arg,
                          IFormatProvider formatProvider)
   {
      if (!this.Equals(formatProvider))
      {
         return null;
      }
      else
      {
         if (String.IsNullOrEmpty(format))
            format = "G";

         string customerString = arg.ToString();
         if (customerString.Length < 8)
            customerString = customerString.PadLeft(8, '0');

         format = format.ToUpper();
         switch (format)
         {   
            case "G":
               return customerString.Substring(0, 1) + "-" +
                                customerString.Substring(1, 5) + "-" +
                                customerString.Substring(6);
            case "S":
               return customerString.Substring(0, 1) + "/" +
                                customerString.Substring(1, 5) + "/" +
                                customerString.Substring(6);
            case "P":            
               return customerString.Substring(0, 1) + "." +
                                customerString.Substring(1, 5) + "." +
                                customerString.Substring(6);
            default:
               throw new FormatException(
                         String.Format("The '{0}' format specifier is not supported.", format));                                
         }
      }
   }
}
// The example displays the following output:
//       7-92031-59
//       7-92031-59
//       7/92031/59
//       7.92031.59
//       The 'X' format specifier is not supported.

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.