Friday 6 April 2012

IFORMATABLE INTERFACE



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public struct ComplexNumber : IFormattable
    {
        private double real;
        private double imaginary;

        public ComplexNumber(double real, double imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }
        public string ToString(string mask, IFormatProvider ifp)
        {
            if (mask == "i" || mask == "j")
            {
                return this.real.ToString() + (this.imaginary >= 0 ? "+" : "") + this.imaginary.ToString() + mask;
            }
            else
            {
                return "";
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ComplexNumber c = new ComplexNumber(5, -6);
            Console.WriteLine("Format 1: {0:i}", c);
            Console.WriteLine("Format 2: {0:j}", c);
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment