IFormatProvider interface

In this chapter you will learn:

  1. How to implement IFormatProvider interface

Implement IFormatProvider interface

The following code implements IFormatProvider to format a complex number.

using System;/*from j  ava  2s. c o  m*/
using System.Text;
using System.Globalization;

public class ComplexDbgFormatter : ICustomFormatter, IFormatProvider
{
    public object GetFormat( Type formatType ) {
        if( formatType == typeof(ICustomFormatter) ) {
            return this;
        } else {
            return CultureInfo.CurrentCulture.
                GetFormat( formatType );
        }
    }

    public string Format( string format, object arg, IFormatProvider formatProvider ) {
        if( arg.GetType() == typeof(Complex) && format == "DBG" ) {
            Complex cpx = (Complex) arg;

            StringBuilder sb = new StringBuilder();
            sb.Append( arg.GetType().ToString() + " " );
            sb.AppendFormat( "Real:{0} ", cpx.Real );
            sb.AppendFormat( "Img: {0} ", cpx.Img );
            return sb.ToString();
        } else {
            IFormattable formatable = arg as IFormattable;
            if( formatable != null ) {
                return formatable.ToString( format, formatProvider );
            } else {
                return arg.ToString();
            }
        }
    }
}

public struct Complex : IFormattable
{
    public Complex( double Real, double Img ) {
        this.Real = Real;
        this.Img = Img;
    }

    public string ToString( string format, IFormatProvider formatProvider ) {
        StringBuilder sb = new StringBuilder();
        sb.Append( "( " + Real.ToString(format, formatProvider) );
        sb.Append( " : " + Img.ToString(format, formatProvider) );
        sb.Append( " )" );

        return sb.ToString();
    }

    public double Real;
    public double Img;
}

public class MainClass
{
    static void Main() {
        CultureInfo local = CultureInfo.CurrentCulture;
        CultureInfo germany = new CultureInfo( "de-DE" );

        Complex cpx = new Complex( 12.3456, 1234.56 );

        string strCpx = cpx.ToString( "F", local );
        Console.WriteLine( strCpx );

        strCpx = cpx.ToString( "F", germany );
        Console.WriteLine( strCpx );

        ComplexDbgFormatter dbgFormatter = new ComplexDbgFormatter();
        strCpx = String.Format( dbgFormatter,"{0:DBG}",  cpx );
        Console.WriteLine( "\nDebugging output:\n{0}", strCpx );
    }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to implement IFormattable Interface
Home » C# Tutorial » System Interface
ICloneable interface
IComparable interface
IComparer interface
IConvertible interface
IDisposable interface
IEnumerable interface
IEquatable interface
IFormatProvider interface
IFormattable interface