Export (0) Print
Expand All

IFormatProvider.GetFormat Method

Returns an object that provides formatting services for the specified type.

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

Object GetFormat(
	Type formatType
)

Parameters

formatType
Type: System.Type
An object that specifies the type of format object to return.

Return Value

Type: System.Object
An instance of the object specified by formatType, if the IFormatProvider implementation can supply that type of object; otherwise, null.

GetFormat is a callback method that formatting and parsing methods invoke to retrieve information about the format of the input string in parsing operations or the format of the output string in formatting operations. In the formatType parameter, the formatting or parsing method passes the type of object it requires to perform its operation. If the IFormatProvider implementation can supply this formatting or parsing object, it returns that object. If not, it returns null.

For example, in the call to the Int32.ToString(IFormatProvider) method, the method argument is an IFormatProvider object that provides information about how the string representation of the current integer instance might be formatted. When the runtime executes the method, it calls the IFormatProvider object's GetFormat method and passes it a Type object that represents the NumberFormatInfo type. If the IFormatProvider object can supply a NumberFormatInfo object, it returns that object. If it cannot supply an object of that type, it returns null.

You can implement the IFormatProvider interface and the GetFormat method in classes that provide custom formatting or parsing services. The IFormatProvider implementation is then passed as an argument to any overload of a parsing or formatting method that has a parameter of type IFormatProvider, such as String.Format(IFormatProvider, String, Object[]), Int32.ToString(String, IFormatProvider), or DateTime.Parse(String, IFormatProvider).

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 itself if the formatType parameter refers to a class that implements ICustomFormatter; otherwise, GetFormat returns null.


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) 
   {
      // Provide default formatting if arg is not an Int64.
      if (arg.GetType() != typeof(Int64))
         try {
            return HandleOtherFormats(fmt, arg); 
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
         }

      // Provide default formatting for unsupported format strings.
      fmt = fmt.ToUpper(CultureInfo.InvariantCulture);
      if (! (fmt == "H" || fmt == "I")) 
         return HandleOtherFormats(fmt, arg);

      // 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);   

      if (fmt.ToUpper() == "I")                    // Integer-only format. 
         return result;
      // Add hyphens for H format specifier.
      else if (fmt.ToUpper() == "H")               // Hyphenated format.
         return result.Substring(0, 5) + "-" + result.Substring(5, 3) + "-" + result.Substring(8);
      // Return string representation of argument for any other formatting code.
      else
         try {
            return HandleOtherFormats(fmt, arg); 
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
         }
   }

   private string HandleOtherFormats(string format, object arg)
   {
      if (arg is IFormattable) 
         return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
      else if (arg != null)
         return arg.ToString();
      else
         return String.Empty;
   }
}


An instance of the AcctNumberFormat class can then be passed as an argument to a method that provides formatting or parsing services. For example, the following code passes an AcctNumberFormat class to the String.Format(IFormatProvider, String, Object[]) method to generate a formatted 12-digit account number.


public enum DaysOfWeek { Monday=1, Tuesday=2 };

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      long acctNumber;
      double balance; 
      DaysOfWeek wday; 
      string output;

      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);
      outputBlock.Text += output + "\n";

      wday = DaysOfWeek.Tuesday;
      output = String.Format(new AcctNumberFormat(), 
                             "On {2}, the balance of account {0:I} was {1:C2}.", 
                             acctNumber, balance, wday);
      outputBlock.Text += output + "\n";
   }
}
// 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.


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

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

Community Additions

ADD
Show:
© 2014 Microsoft