Please navigate to the bottom of the page for Table of Contents

Friday, May 27, 2011

Operator overloading and pairing rules in C#

What is the problem in the following code snippet?

namespace ConsoleApplication1
{
struct Point
{
int X;
int Y;

public static bool operator ==(Point p1, Point p2)
{
return ((p1.X == p2.X) && (p1.Y == p2.Y));
}
}
}


When you overload equality (==, !=) and comparison (<, >, <=, >=) operators, special pairing and overriding rules are enforced by C# compiler. For the above example, the compiler generates 2 warnings and the 1 error:



  • Warning: 'ConsoleApplication1.Point' defines operator == or operator != but does not override Object.GetHashCode()

  • Warning: 'ConsoleApplication1.Point' defines operator == or operator != but does not override Object.Equals(object o)

  • Error: The operator 'ConsoleApplication1.Point.operator ==(ConsoleApplication1.Point, ConsoleApplication1.Point)' requires a matching operator '!=' to also be defined   

Rule 1: If you overload the equality operators (== and !=), it is good practice to override the GetHashCode() and Equals() methods. Reason: Collections and HashTables rely on equality relations to work reliably.


Rule 2: If you overload one operation that is part of a pair (for example, == and !=), you are required to implement the other operator.


Rule 3: If you overload the comparison operators (< and >), it is a good practice to implement IComparable and IComparable<T> for the same reasons defined for rule 1.

6 comments:

  1. Can we have a correct code for the above code snippet please?

    ReplyDelete
  2. There are all the way the bewts Boneka Wisuda of optimization and the best marketing which you can think about.
    Backlinks is just like brand After Boneka Wisuda.
    looking into a handful of the blog posts on your blog, Boneka Wisuda
    I truly like your technique of blogging. Boneka Wisuda I book marked it to my bookmark site list and will be checking back soon. Please visit my
    web site as well and let me know how you feel.Boneka Wisuda advertising which carried out offline throuh press Boneka Wisuda.


    ReplyDelete
  3. Nice Blog.Thank you for Sharing. We are leading erp software software solution providers in chennai.
    erp in chennai | cloud erp software in chennai

    ReplyDelete
  4. You are doing a great job. You inspire me to write for other. Thank you very much. I would like to appreciate your work for good accuracy and got informative knowledge from here. Python Training in Chennai

    ReplyDelete