Implementation of IFormattable : IFormattable « Class « C# / CSharp Tutorial






using System;

public class MyClass : IFormattable
{
    private string title;
    private string[] names;

    public MyClass(string title, params string[] names)
    {
        this.title = title;
        this.names = names;
    }

    public override string ToString()
    {
        return ToString("G", null);
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        string result = null;

        if (format == null) 
            format = "G";

        switch (format.ToUpper()[0])
        {
            case 'S':
                result = "S." ;
                break;

            case 'P':
                result = "P. ";
                break;

            case 'I':
                result = "I. ";
                break;

            case 'G':
            default:
                result = "G. ";
                break;
        }
        return result;
    }
}

public class MainClass
{
    public static void Main()
    {
        MyClass person = new MyClass("Mr", "A", "B", "C", "D");

        System.Console.WriteLine("Dear {0:G},", person);
        System.Console.WriteLine("Dear {0:P},", person);
        System.Console.WriteLine("Dear {0:I},", person);
        System.Console.WriteLine("Dear {0},", person);
        System.Console.WriteLine("Dear {0:S},", person);

    }
}
Dear G. ,
Dear P. ,
Dear I. ,
Dear G. ,
Dear S.,








7.56.IFormattable
7.56.1.Implementation of IFormattable
7.56.2.Implements IFormattable with switch statement
7.56.3.Formattable Vector
7.56.4.implements IFormatProvider, ICustomFormatter