Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 11-42 extracted from chapter Classes and objects


Listing 11-41<     > Listing 12-1


This listing can be compiled with the command line:
csc.exe /target:exe Example_11_42.cs
Errors: 0 Warnings: 2


Example_11_42.cs
public class Distance {
   private double m_Measure = 0.0;
   public Distance(double d) { m_Measure = d; }
   public override bool Equals( object obj ) {
      Distance d = obj as Distance;
      // Check that we are effectively comparing with a Distance.
      // With the same test, handle also the case where 'obj' is null.
      if( !Distance.ReferenceEquals( d , null ) )
         // Comparison on content.
         return m_Measure == d.m_Measure;
      return false;
   }
   public static bool operator ==(Distance d1, object d2) {
      // Handle the case where one or two distances are null.
      ifDistance.ReferenceEquals( d1 , null ) ) {
         return Distance.ReferenceEquals( d2 , null );
      }
      return d1.Equals(d2);
   }
   public static bool operator !=(Distance d1, object d2) {
      return ! (d1 == d2) ;
   }
}
class Program {
   static void Main() {
      Distance d1 = new Distance(5.2);
      Distance d2 = new Distance(5.2);
      Distance d3 = new Distance(7.3);
      Distance d4 = null;
      // All the following assertions are true.
      System.Diagnostics.Debug.Assert( d1 == d2 );
      System.Diagnostics.Debug.Assert( d1 != d3 );
      System.Diagnostics.Debug.Assert( d1 != null );
      System.Diagnostics.Debug.Assert( null != d1 );
      System.Diagnostics.Debug.Assert( !(d1 == null) );
      System.Diagnostics.Debug.Assert( !(null == d1) );
      System.Diagnostics.Debug.Assert( d4 == null );
   }
}	
Copyright Patrick Smacchia 2006 2007