Table of contents Home page
using System; public struct ComplexNumber : IEquatable<ComplexNumber> { private double real; private double imaginary; public ComplexNumber(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } public bool Equals(ComplexNumber c) { return this.real == c.real && this.imaginary == c.imaginary; } public override bool Equals(Object obj) { if (obj == null) return base.Equals(obj); if (!(obj is ComplexNumber)) { throw new InvalidCastException("The 'obj' argument is not a ComplexNumber object."); } else { return Equals((ComplexNumber)obj); } } public override int GetHashCode() // Needed for suppressing a compiler warning { return base.GetHashCode(); } override public string ToString() { return this.real.ToString() + (this.imaginary >= 0 ? "+" : "") + this.imaginary.ToString() + "i"; } } public class Program { public static void Main(string[] args) { try { ComplexNumber c1 = new ComplexNumber(5, -6); ComplexNumber c2 = new ComplexNumber(5, 6); Console.WriteLine(c1.Equals(c2)); c2 = new ComplexNumber(5, -6); Console.WriteLine(c1.Equals(c2)); object c3 = new ComplexNumber(5, 6); Console.WriteLine(c1.Equals(c3)); c3 = new ComplexNumber(5, -6); Console.WriteLine(c1.Equals(c3)); DateTime d = new DateTime(); Console.WriteLine(c1.Equals(d)); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); } }