0 out of 1 rated this helpful - Rate this topic

ICustomFormatter.Format Method

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)
string Format(
	string format,
	Object arg,
	IFormatProvider formatProvider
)

Parameters

format
Type: System.String
A format string containing formatting specifications.
arg
Type: System.Object
An object to format.
formatProvider
Type: System.IFormatProvider
An 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 format string. For example, in the following statement, the ICustomFormatter.Format method is called three times.


Console.WriteLine(String.Format(new BinaryFormatter(), 
                                "{0} (binary: {0:B}) (hex: {0:H})", byteValue));


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 null. If format is null, 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 null, 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 (arg is IFormattable) 
   return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
else if (arg != null)
   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 null, it calls the arg parameter's IFormattable.ToString implementation, if one exists, or its parameterless ToString method, if one does not. If arg is null, the method returns String.Empty.


using System;
using System.Globalization;
using System.Numerics;

public class BinaryFormatter : IFormatProvider, ICustomFormatter
{
   // IFormatProvider.GetFormat implementation.
   public object GetFormat(Type formatType)
   {
      // Determine whether custom formatting object is requested.
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }   

   // Format number in binary (B), octal (O), or hexadecimal (H).
   public string Format(string format, object arg, IFormatProvider formatProvider)
   {
      // Handle format string.
      int baseNumber;
      // Handle null or empty format string, string with precision specifier.
      string thisFmt = String.Empty;
      // Extract first character of format string (precision specifiers
      // are not supported).
      if (! String.IsNullOrEmpty(format))
         thisFmt = format.Length > 1 ? format.Substring(0, 1) : format;


      // Get a byte array representing the numeric value.
      byte[] bytes;
      if (arg is sbyte)
      {
         string byteString = ((sbyte) arg).ToString("X2");
         bytes = new byte[1] { Byte.Parse(byteString, System.Globalization.NumberStyles.HexNumber ) };
      }
      else if (arg is byte) {
         bytes = new byte[1] { (byte) arg };
      }   
      else if (arg is short) {
         bytes = BitConverter.GetBytes((short) arg);
      }   
      else if (arg is int) {
         bytes = BitConverter.GetBytes((int) arg);
      }   
      else if (arg is long) {
         bytes = BitConverter.GetBytes((long) arg);
      }
      else if (arg is ushort) {
         bytes = BitConverter.GetBytes((ushort) arg);
      }
      else if (arg is uint) {
         bytes = BitConverter.GetBytes((uint) arg);
      }
      else if (arg is ulong) {
         bytes = BitConverter.GetBytes((ulong) arg);                  
      }
      else if (arg is BigInteger) {
         bytes = ((BigInteger) arg).ToByteArray();
      }
      else {
         try {
            return HandleOtherFormats(format, arg); 
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
         }
      }

      switch (thisFmt.ToUpper())
      {
         // Binary formatting.
         case "B":
            baseNumber = 2;
            break;        
         case "O":
            baseNumber = 8;
            break;
         case "H":
            baseNumber = 16;
            break;
         // Handle unsupported format strings.
         default:
         try {
            return HandleOtherFormats(format, arg); 
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
         }
      }

      // Return a formatted string.
      string numericString = String.Empty;
      for (int ctr = bytes.GetUpperBound(0); ctr >= bytes.GetLowerBound(0); ctr--)
      {
         string byteString = Convert.ToString(bytes[ctr], baseNumber);
         if (baseNumber == 2)
            byteString = new String('0', 8 - byteString.Length) + byteString;
         else if (baseNumber == 8)
            byteString = new String('0', 4 - byteString.Length) + byteString;
         // Base is 16.
         else     
            byteString = new String('0', 2 - byteString.Length) + byteString;

         numericString +=  byteString + " ";
      }
      return numericString.Trim();
   }

   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;
   }
}


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 class Example
{
   public static void Main()
   {
      Console.WindowWidth = 100;

      byte byteValue = 124;
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{0} (binary: {0:B}) (hex: {0:H})", byteValue));

      int intValue = 23045;
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{0} (binary: {0:B}) (hex: {0:H})", intValue));

      ulong ulngValue = 31906574882;
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{0}\n   (binary: {0:B})\n   (hex: {0:H})", 
                                      ulngValue));

      BigInteger bigIntValue = BigInteger.Multiply(Int64.MaxValue, 2);
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{0}\n   (binary: {0:B})\n   (hex: {0:H})", 
                                      bigIntValue));
   }
}
// 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)
//    18446744073709551614
//       (binary: 00000000 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111110)
//       (hex: 00 ff ff ff ff ff ff ff fe)


.NET Framework

Supported in: 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

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.