CSharp - IFormatProvider and ICustomFormatter

Introduction

All format providers implement IFormatProvider:

public interface IFormatProvider { 
   object GetFormat (Type formatType); 
}

The method allows CultureInfo to defer to an appropriate NumberFormatInfo or DateTimeInfo object to do the work.

By implementing IFormatProvider-along with ICustomFormatter-you can write your own format provider that works in conjunction with existing types.

ICustomFormatter defines a single method as follows:

string Format (string format, object arg, IFormatProvider formatProvider);

The following custom format provider writes numbers as words:

Demo

using System;
using System.Globalization;
using System.Text;

class MainClass/*from   w  ww .  j ava 2s  .c  o  m*/
{
    public static void Main(string[] args)
    {
        double n = -123456789.456789;
        IFormatProvider fp = new EncryptFormatProvider();
        Console.WriteLine(string.Format(fp, "{0:C} in words is {0:W}", n));


    }
}

class EncryptFormatProvider : IFormatProvider, ICustomFormatter
{
    static readonly string[] _numberWords = "! @ # $ % ^ & * ` ~ : : ' { | = [ ] ".Split();

    IFormatProvider _parent;

    public EncryptFormatProvider() : this(CultureInfo.CurrentCulture) { }
    public EncryptFormatProvider(IFormatProvider parent)
    {
        _parent = parent;
    }
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter)) return this;
        return null;
    }

    public string Format(string format, object arg, IFormatProvider prov)
    {
        if (arg == null || format != "W")
            return string.Format(_parent, "{0:" + format + "}", arg);

        StringBuilder result = new StringBuilder();
        string digitList = string.Format(CultureInfo.InvariantCulture,
                                          "{0}", arg);
        foreach (char digit in digitList)
        {
            int i = "0123456789-.".IndexOf(digit);
            if (i == -1) continue;
            if (result.Length > 0) result.Append(' ');
            result.Append(_numberWords[i]);
        }
        return result.ToString();
    }
}

Result