using System; namespace DemoMoreTypesMembers { public struct Money { // Fields. private double mAmount; private const string mCurrencySymbol = "$"; // Constructor. public Money(double amount) { this.mAmount = amount; } // Arithmetic operators. public static Money operator +(Money m1, Money m2) { return new Money(m1.mAmount + m2.mAmount); } public static Money operator -(Money m1, Money m2) { return new Money(m1.mAmount - m2.mAmount); } public static Money operator ++(Money m1) { return m1 + new Money(1.0); } public static Money operator --(Money m1) { return m1 - new Money(1.0); } // Comparison operators. public static bool operator ==(Money m1, Money m2) { return m1.mAmount == m2.mAmount; } public static bool operator !=(Money m1, Money m2) { return !(m1 == m2); } public static bool operator >(Money m1, Money m2) { return m1.mAmount > m2.mAmount; } public static bool operator <(Money m1, Money m2) { return m1.mAmount < m2.mAmount; } public static bool operator >=(Money m1, Money m2) { return m1.mAmount >= m2.mAmount; } public static bool operator <=(Money m1, Money m2) { return m1.mAmount <= m2.mAmount; } // Object-class overrides. public override bool Equals(object other) { if (!(other is Money)) return false; else return (this == (Money)other); } public override int GetHashCode() { return (int)(mAmount * 100); } public override string ToString() { return mCurrencySymbol + this.mAmount; } } static class OperatorsDemo { public static void DoDemo() { Console.WriteLine("\nOperatorsDemo"); Console.WriteLine("------------------------------------------------------"); Money dosh1 = new Money(27.50); Money dosh2 = new Money(10.30); Console.WriteLine("Initial values:"); Console.WriteLine("dosh1: {0}", dosh1); Console.WriteLine("dosh2: {0}", dosh2); Console.WriteLine("\nIllustrate + and - operators:"); Console.WriteLine("dosh1 + dosh2: {0}", dosh1 + dosh2); Console.WriteLine("dosh1 - dosh2: {0}", dosh1 - dosh2); Console.WriteLine("\nIllustrate += and -= operators:"); Money dosh3 = new Money(100.0); dosh3 += dosh1; dosh3 -= dosh2; Console.WriteLine("dosh3: {0}", dosh3); Console.WriteLine("\nIllustrate ++ and -- operators:"); Money dosh4 = ++dosh1; Money dosh5 = dosh2--; Console.WriteLine("dosh1: {0}", dosh1); Console.WriteLine("dosh4: {0}", dosh4); Console.WriteLine("dosh2: {0}", dosh2); Console.WriteLine("dosh5: {0}", dosh5); Console.WriteLine("\nIllustrate comparison operators:"); Console.WriteLine("dosh1 and dosh2 {0}", (dosh1 == dosh2) ? "equal" : "different"); Console.WriteLine("dosh1 and dosh2 {0}", (dosh1 != dosh2) ? "different" : "equal"); Console.WriteLine("dosh1 is {0}> dosh2", (dosh1 > dosh2) ? "" : "NOT "); Console.WriteLine("dosh1 is {0}< dosh2", (dosh1 < dosh2) ? "" : "NOT "); Console.WriteLine("dosh1 is {0}>= dosh2", (dosh1 >= dosh2) ? "" : "NOT "); Console.WriteLine("dosh1 is {0}<= dosh2", (dosh1 <= dosh2) ? "" : "NOT "); Console.ReadLine(); } } }