C#
  Home arrow C# arrow Page 3 - Overloading Operators in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Overloading Operators in C#
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2008-10-30

    Table of Contents:
  • Overloading Operators in C#
  • Operator Overloading
  • Overloading Equality and Comparison Operators
  • Overloading true and false

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Overloading Operators in C# - Overloading Equality and Comparison Operators


    (Page 3 of 4 )

    Equality and comparison operators are sometimes overridden when writing structs, and in rare cases when writing classes. Special rules and obligations come with overloading the equality and comparison operators, which we explain in Chapter 6. A summary of these rules is as follows:

    Pairing

    The C# compiler enforces operators that are logical pairs to both be defined. These operators are (==!=), (<>), and (<= >=).

    Equalsand GetHashCode

    In most cases, if you overload (==) and (!=), you need to override theEquals andGetHashCode methods defined onobjectin order to get meaningful behavior. The C# compiler will give a warning if you do not do this. (See the section “Equality comparison ” in Chapter 6 for more details.)

    IComparableand IComparable<T>

    If you overload (<>) and (<= >=), you should implementIComparableand IComparable<T>.

    Custom Implicit and Explicit Conversions

    Implicit and explicit conversions are overloadable operators. These conversions are typically overloaded to make converting between strongly related types (such as numeric types) concise and natural.

    To convert between weakly related types, the following strategies are more suitable:

    1. Write a constructor that has a parameter of the type to convert from.
    2. WriteToXXX andFromXXX methods to convert between types.

    As explained in the discussion on types, the rationale behind implicit conversions is that they are guaranteed to succeed and do not lose information during the conversion. Conversely, an explicit conversion should be required either when runtime circumstances will determine whether the conversion will succeed or if information may be lost during the conversion.

    In this example, we define conversions between our musicalNotetype and a double (which represents the frequency in hertz of that note):

      ...
      // Convert to hertz
      public static implicit operator double(Note x)
      {

        return 440 * Math.Pow (2,(double) x.value / 12 );
      }
     
    // Convert from hertz (only accurate to nearest semitone)
      public static explicit operator Note(double x)
      {
        return new Note ((int) (0.5 + 12 * (Math.Log(x/440) / Math.Log(2)) ));
      }
      ...

      Note n =(Note)554.37;  // explicit conversion
      double x = n;          // implicit conversion

    Following our own guidelines, this example might be better implemented with aToFrequencymethod (and a staticFromFrequencymethod) instead of implicit and explicit operators.

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C# 3.0 in a Nutshell, Third Edition, A...
     

    Buy this book now. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Coding a CRC-Generating Algorithm in C
    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek