Implements IFormattable with switch statement : IFormattable « Class « C# / CSharp Tutorial






using System;


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

    public Employee(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 = names[0][0] + "." + names[names.Length - 1];
                break;
            case 'P':
                if (title != null && title.Length != 0) {
                    result = title + ".";
                }
                break;

            case 'I':
                result = names[0];
                break;
            case 'G':
            default:
                result = names[0] + " " + names[names.Length - 1];
                break;
        }
        return result;
    }
}

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

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








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